skip to content

Search

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

  1. 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.

  2. Monitor lock: unlock(m) HB every later lock(m) on the same monitor.

    synchronized (lock) { x = 1; }      // thread A: unlock publishes x
    synchronized (lock) { print(x); }   // thread B: lock sees x == 1

    Same lock object on both sides, or there is no edge.

  3. 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 volatile

    A volatile write publishes everything written before it, not just the volatile itself.

  4. Thread start: t.start() HB every action in t. The new thread sees everything the parent did before start().

  5. Thread join: every action in t HB the return of t.join() (or isAlive() returning false) in another thread. After join(), you can safely read what the thread wrote.

  6. Final field: after a constructor finishes, other threads see the correct values of its final fields (and what they reference) without synchronization. Holds only if this doesn’t escape during construction.

  7. 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

RuleEdge from → to
Program orderearlier statement → later statement (same thread)
Monitor lockunlock → next lock (same monitor)
Volatilewrite → later read (same variable)
Thread startstart() → thread body
Thread jointhread body → join() return
Final fieldend of constructor → any thread reading the field
TransitivityA→B and B→C gives A→C