What is the Java Memory Model? The JMM explains why the original double-checked locking optimization is broken and how it can be fixed.
It answers the seemingly simple question, when does a read of myVariable see 3 after the assignment
public int myVariable = 3;
The JMM defines a partial-ordering called happens-before on all actions in a program. For example, in the figure below,

Figure by Brian Goetz
All the actions prior to the unlock M in Thread A happens-before the lock M in Thread B. This guarantees that j = y = 1. Without the JMM j = y = 1 could not be guaranteed because of the various "quirks" in the hardware and compiler layer (processor cache coherence, compiler reordering, etc.).
Actions include
- reads and writes to variables
- locks and unlocks of monitors
- starting and joining with threads
The rules for happens-before are
- Program order rule. Within a thread actions happen in program order.
- Monitor lock rule. Unlock on monitor happens-before every subsequent lock on the same monitor.
- Volatile variable rule. A write to a volatile happens-before every subsequent read of that volatile.
- Thread start rule. Thread.start happens-before actions in the Thread
- Thread termination rule. Actions in a thread happens-before other threads detect the thread's termination.
- Interruption rule. A thread calling interrupt on another thread happens before the interrupted thread detects the interrupt.
- Finalizer rule. End of object construction happens-before start of object finalization.
- Transitivity. If A happens-before B, and B happens-before C, then A happens-before C.
There you have it, the Java Memory Model in 500 words. This summary has been taken from Brian Goetz's Java Concurrency in Practice, which I can't recommend enough.
The Java Memory Model in 7 words: ALL YOUR MEMORY ARE BELONG TO US! ;-)
Posted by: design | August 19, 2008 at 09:16 AM