The Java memory model question 18 of 180 senior
What does final guarantee, and what breaks that guarantee?
- Nothing,
finalis a compile-time check only - Correct: Final fields set in the constructor are visible to any thread that sees the object, unless
thisescaped during construction - Final fields are automatically volatile
- It guarantees the referenced object is immutable too
There is a freeze at the end of the constructor: any thread that obtains a reference to the object
through a normal read is guaranteed to see the final fields with their constructed values, with no
synchronisation of any kind. This is what makes String and the immutable collections safe to share
freely.
The guarantee has one condition and one limit. The condition: this must not escape during
construction. Registering a listener, starting a thread or passing this to a callback from a
constructor hands out a reference before the freeze, and the guarantee is void. The limit: final
freezes the reference, not the object behind it. A final List field whose list is mutated is not
thread safe in the slightest.