Java_Memory_Model_Interview_Problems
Java_Memory_Model_Interview_Problems
How does 'happens-before' work in the JMM and what does it guarantee?
The 'happens-before' relationship defines when one action's effects are visible to
another.
If A happens-before B, then:
All memory writes in A are guaranteed visible to B.
B cannot be reordered before A.
Examples of happens-before relationships:
Thread.start() happens-before any actions in the started thread.
Thread.join() happens-after the thread has terminated.
Locking via synchronized ensures happens-before between unlock and subsequent lock.
Writing to a volatile variable happens-before reading the same variable.
What are the semantics of final fields in the Java Memory Model?
Final fields get special treatment in the JMM for immutability and safe publication.
Once a final field is set in the constructor and the constructor completes normally:
Other threads will see the correctly constructed object, even without synchronization.
Conditions:
The object must not be published (escaped) during construction.
All final fields must be initialized in the constructor.
This guarantees safe publication without explicit synchronization.