How does the JVM handle final variables differently under the hood?
- Related: stackoverflow.com/q/3697988/3651800Matt Coubrough– Matt Coubrough2014-12-09 00:41:40 +00:00Commented Dec 9, 2014 at 0:41
- 1What is the question targetting? Things like: It uses the knowledge that the value won't change to optimize, for example it doesn't need to re-read the value in multi threaded code?zapl– zapl2014-12-09 00:42:45 +00:00Commented Dec 9, 2014 at 0:42
- @MattCoubrough: Related, but not a duplicate. That other question is about static final.Thilo– Thilo2014-12-09 00:57:53 +00:00Commented Dec 9, 2014 at 0:57
- @Thilo Can you re-post the link?Sotirios Delimanolis– Sotirios Delimanolis2014-12-09 00:58:27 +00:00Commented Dec 9, 2014 at 0:58
- @Thilo - I know - which is why I wrote Related and didn't flag as a duplicate.Matt Coubrough– Matt Coubrough2014-12-09 00:58:46 +00:00Commented Dec 9, 2014 at 0:58
| Show 1 more comment
1 Answer
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
finalfields must be visible to all threads. - The fields on any object accessed via a
finalreference 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
finaland 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 afinalreference. - 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).