Java Core & JVM (50 Qs)•Part 3: JVM Internals, Low-Latency Systems & Production Tuning (25 - 35)
How does the Java Memory Model define happens-before relationships and instruction reordering?
senior LeveljavaJVM Internals
In Simple Words: Modern CPUs and compilers reorder machine instructions aggressively to maximize CPU pipeline execution throughput. The Java Memory Model (JMM) defines formal rules called happens-before to guarantee that memory writes performed by one thread are predictably visible to other threads.
Core Happens-Before Rules:
- Program Order Rule: Each action in a single thread happens-before every subsequent action in that same thread.
- Volatile Variable Rule: A write to a
volatilevariable happens-before every subsequent read of that same variable. - Monitor Lock Rule: An unlock on a monitor lock happens-before every subsequent lock on that same monitor.
- Thread Start Rule: A call to
Thread.start()happens-before any action in the started thread. - Transitivity: If A happens-before B, and B happens-before C, then A happens-before C.