Java Memory Model and "happens-before"
happens-before (HB): if action A HB action B, then everything A did (writes) is visible to B, and A is ordered before B. It is a visibility guarantee, not a statement about wall-clock time. Without an HB edge between two threads, a read may see stale or reordered data.
The rules
-
Program order: within one thread, each action HB every later action in that thread’s code. Single-threaded code behaves as written. This is the only rule that needs no other thread.
-
Monitor lock:
unlock(m)HB every laterlock(m)on the same monitor.synchronized (lock) { x = 1; } // thread A: unlock publishes x synchronized (lock) { print(x); } // thread B: lock sees x == 1Same lock object on both sides, or there is no edge.
-
Volatile variable: a write to a volatile field HB every later read of that same field.
data = 42; ready = true; // A (ready is volatile) if (ready) print(data); // B sees 42, even though data is not volatileA volatile write publishes everything written before it, not just the volatile itself.
-
Thread start:
t.start()HB every action int. The new thread sees everything the parent did beforestart(). -
Thread join: every action in
tHB the return oft.join()(orisAlive()returning false) in another thread. Afterjoin(), you can safely read what the thread wrote. -
Final field: after a constructor finishes, other threads see the correct values of its
finalfields (and what they reference) without synchronization. Holds only ifthisdoesn’t escape during construction. -
Transitivity: if A HB B and B HB C, then A HB C. This is what makes rule 3 chain: write data → write volatile → read volatile → read data.
Quick recall
| Rule | Edge from → to |
|---|---|
| Program order | earlier statement → later statement (same thread) |
| Monitor lock | unlock → next lock (same monitor) |
| Volatile | write → later read (same variable) |
| Thread start | start() → thread body |
| Thread join | thread body → join() return |
| Final field | end of constructor → any thread reading the field |
| Transitivity | A→B and B→C gives A→C |