Java Memory Model¶
The Java Memory Model (JMM) defines which writes a thread is allowed to observe and which reorderings preserve legal behavior. Source-code order alone does not create inter-thread visibility.
Happens-before¶
If action A happens-before action B, A's effects are visible to B and ordered before it. Important edges include:
- program order within one thread;
- an unlock before a later lock of the same monitor;
- a volatile write before a later read of that variable;
- actions before
Thread.start()becoming visible to the started thread; - actions in a thread becoming visible after successful
join(); - transitivity of the relation.
Volatile is not compound atomicity¶
private volatile boolean stopped;
void stop() {
stopped = true;
}
void runLoop() {
while (!stopped) doOneUnit();
}
volatile fits an independent visibility flag. It does not make count++
atomic because increment is a read-modify-write sequence. Use a lock or an
appropriate atomic class for compound updates.
Safe publication¶
An object must be published through a happens-before edge before other threads use it. Locking, volatile references, static initialization, concurrent collections, and task-submission mechanisms can establish safe publication under their contracts. Final fields receive additional initialization guarantees when the object does not escape during construction.
Reasoning rule¶
Do not infer legal concurrent behavior from what one processor or one test run happened to do. Identify shared mutable state and the happens-before path for every required observation.