What does the JVM do with a final variable in a class?

南楼画角 提交于 2019-12-05 01:20:45

问题


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



来源:https://stackoverflow.com/questions/27369584/what-does-the-jvm-do-with-a-final-variable-in-a-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!