Java / Java Concurrency and Multi Threading in Java 17 and Java 21 Interview questions
How is the Java Memory Model relevant to concurrent programming?
The Java Memory Model (JMM), formalized in JSR-133, defines the rules for when a write to a shared variable by one thread is guaranteed to be visible to a read by another thread, and what reorderings of instructions the compiler and CPU are allowed to perform.
Without these rules, a compiler could legally cache a field's value in a register and never re-read main memory, or reorder independent statements for performance, either of which could cause one thread to never observe another thread's update, or observe partially constructed state.
The JMM defines this through happens-before relationships: if action A happens-before action B, every effect of A is guaranteed visible to B. Common sources of happens-before edges include program order within a single thread, unlocking a monitor before another thread locks it, writing a volatile field before another thread reads it, and a call to Thread.start() before that thread's first action.
Practically, this is why unsynchronized access to shared mutable fields is unsafe even on hardware where a "torn read" seems unlikely: the model, not just the hardware, permits stale or reordered reads unless a proper happens-before edge exists.
More Related questions...