What does the JVM do with a final variable in a cl

2019-03-30 19:25发布

问题:

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 actually final, but in practice never change) via a final 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).



标签: java jvm final