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).