Do javac or Hotspot automatically add 'final' as an optimisation of invariant variables?

后端 未结 4 2025
北荒
北荒 2021-01-13 11:40

The consensus seems to be that there is a performance benefit to marking member variables as final because they never need reloading from main memory. My question is, do jav

4条回答
  •  南方客
    南方客 (楼主)
    2021-01-13 12:14

    Allowing javac to do this would be a blunder. As there might be code in a different jar which may rely on the code being compiled (modularity), changing code at compile time for optimization sake is not a feasible option.

    As for the second argument "never need reloading from the main memory", one needs to remember that most instance variables are cached. final only indicates immutability, it does not guarantee volatility (volatile == always get latest from main memory). Hence the need for locks and volatile keyword in multi-threaded environment.

    As for the case with hotspot, I have no clue, and would like to hear more about it. final constants may be in-lined at compile time, thus allowing moderate performance gains. Reference to a question on in-lining in java

    Edit:

    Note that final indicates immutability needs to be taken with a grain of salt. It does not guarantee that the state cannot change, it only specifies that the object reference can be modified. final indicates immutability for primitive data types

提交回复
热议问题