问题
How does the JVM handle final variables differently under the hood?
回答1:
There is at least one section in the JVM specification about final
's impact on the memory model, and it is quite important for multi-threaded code:
final
fields of an object allow "safe publication":
- When a constructor exits, all
final
fields must be visible to all threads. - The fields on any object accessed via a
final
reference are also guaranteed to be at least as up to date as when the constructor exits. - Taken together, this means that immutable objects (ones where all fields are
final
and are either primitives or references to immutable objects) can be concurrently accessed without synchronization. It is also safe to read "effectively immutable" objects (ones whose fields aren't actuallyfinal
, but in practice never change) via afinal
reference. - Conversely: If your object is accessed by multiple threads, and you don't declare its fields
final
, then you must provide thread-safety by some other means.
But note that the JVM does not enforce actual finality: You can re-assign values using reflection (which of course undermines the safe publication).
来源:https://stackoverflow.com/questions/27369584/what-does-the-jvm-do-with-a-final-variable-in-a-class