Java Core & JVM (50 Qs)•Part 3: JVM Internals, Low-Latency Systems & Production Tuning (25 - 35)
Java Memory Model (JMM): `volatile` and Happens-Before Guarantees.
senior LeveljavaJVM Internals
In Simple Words: Modern CPUs have independent L1/L2 caches and reorder instructions for performance. The JMM defines rules for variable visibility across threads:
volatile:- Visibility: Guarantees that any write to a volatile variable is immediately flushed to main memory and visible to all other threads.
- Instruction Ordering: Prohibits compiler and CPU instruction reordering across the volatile variable read/write via memory barriers.
- Happens-Before: A formal guarantee that memory writes by one thread are guaranteed to be visible to another thread (e.g. unlocking a monitor happens-before any subsequent lock acquisition).