While reading the documentation related to Threads and Locks, a sentence describing final
keyword attracted me:
Correspondingly, compilers are allowed to keep the value of a final field cached in a register and not reload it from memory in situations where a non-final field would have to be reloaded.
Does it mean, that if I declare a final Object object = ...
as an instance variable and then access it (modify its inner state - object.state
) from anonymous inner classes (multiple instances of Runnable
), then the value of object.state
could actually be read/written from/into CPU cache and it (value of object.state
) could be out of sync across those Runnable
instances?
So if I want to be sure, that the value of object.state
is properly propagated across all the threads I have to declare the object
as volatile Object object
instead?
Thank you.
Edit: I have edited my original question. And now I know I misunderstood the documentation so the answer to my last question is NO - volatile/final Object object
has no effect on object.state
- it depends how the object.state
is declared, initialized and/or accessed.
Thanks to the @Burak Serdar for the answer!
When you declare a final Object object=...
, the final value is the reference to the object, not the internal state of the object. It means than nothing can modify object
, it does not say that nothing can modify, say, object.value
. So the variable object
can be cached, which does not mean the internal state of object
can be cached.