Lesson · Java Memory Model (JMM)
Happens-Before: the JMM's one ordering rule
16 min readHappens-Before
Happens-before is the entire visibility story in one relation: if you can draw a chain of edges from a write to a read, the read must see the write. This lesson is the rule table, the two hand-offs everyone uses, and the definition of a data race.
The rule, stated once
A happens-before B means two things at the same time: everything A did is visible to B, and B appears to occur after A. The relation is built from a small set of edges, and every visibility guarantee the JMM offers arrives through it.
Three caveats before the rules. It is a partial order over actions, not a clock: two actions with no edge between them have no order in either direction, and nothing follows about wall-clock time. It is also about actions rather than statements, since one line of source can produce several actions that program order then arranges.
race-conditions already used one edge of this relation in a single sentence: a monitor release makes earlier writes visible to the next acquire. Everything here is that idea written down completely, because the same shape appears on volatile fields, on thread start and join, and on interrupts.
Happens-before is a promise, not a clock: if you can draw the chain, the write is visible.
The rules, complete
Every edge in the relation comes from this table. The first row is free; the middle rows need a shared primitive; the last row is what turns one edge into a guarantee that spans an entire program.
| Rule | Edge it creates | Typical use |
|---|---|---|
| Program order | every action in a thread happens-before the actions that come after it in that thread | the start of every chain you will ever draw |
| Monitor (unlock -> lock) | an unlock of a monitor happens-before every subsequent lock of the same monitor | guarded state: the unlock publishes, the lock acquires |
| Volatile field (write -> read) | a write to a volatile field happens-before every subsequent read of that field | flags and hand-offs between two threads |
| Thread start | a call to start() happens-before the first action of the started thread | passing prepared state into a new thread |
| Thread termination | every action of a thread happens-before another thread's successful return from join() on it | collecting results, and making them visible |
| Interrupt | interrupt() happens-before the interrupted thread detects it, through InterruptedException, isInterrupted or interrupted | shutdown protocols built on interruption |
| Default initialization | the default writes (0, false, null) happen-before any other action | why a field never reads uninitialized memory, unlike C |
| Transitivity | if A happens-before B and B happens-before C, then A happens-before C | chains: one volatile write can publish many fields |
The rules are small; the relation is large, because transitivity chains them. Every visibility guarantee you have used is one of these rows plus the last one.
Walkthrough: the volatile handoff
The canonical two-thread hand-off. A writer sets data and then flips a volatile flag; a reader spins on the flag and then uses the data. Read the chain as three links: program order inside the writer, one volatile edge between the threads, and program order inside the reader.
In the model's own vocabulary: the write to data happens-before the volatile write of ready (program order), the volatile write happens-before the read of ready (the volatile rule), and the read of ready happens-before the read of data (program order again). Transitivity closes the chain, so the read of data must see 42.
static int data; static volatile boolean ready; // writer thread data = 42; // plain write: ordered only by the chain below ready = true; // volatile write: this is the edge // reader thread while (!ready) { } // volatile read: meets the writer's edge int value = data; // must now observe 42
- Program order, writer:
data = 42happens-beforeready = true, because one statement comes before the other in the same thread. - Volatile edge: the write of
readyhappens-before every subsequent read ofready, including the read in the spin loop. - Program order, reader: the read of
readyhappens-before the read ofdatathat follows it. - Transitivity: follow the three edges and the write of
datahappens-before the read ofdata, so the read must return 42. - Notice what did the publishing: not a lock, not a compare-and-swap, not a barrier whose name you have to remember. One volatile write and one volatile read of the same field.
One volatile write and one volatile read of the same field will happily publish three other fields. That is transitivity doing the work.
Happens-before · the volatile hand-off
solid po = program order inside a lane, dashed = the edge that crossesthe chain, link by link
Each link is an edge from the rule table. Transitivity stitches them into one chain, which is why a single volatile field can publish everything written before it.
the other edges that cross lanes
- monitor: an unlock -> a later lock of the same monitor
- volatile: a write -> a later read of the same field
- start: start() -> the first action of the new thread
- join: every action of a thread -> another thread's return from join
- interrupt: interrupt() -> the interrupted thread detects it
- default writes: 0, false and null -> every thread's first action
No other construct creates an edge. Two threads that share no monitors, no volatile fields, no start or join and no interrupt have no happens-before link at all, which is the definition of a data race.
Walkthrough: the monitor handoff
The same chain with a lock in place of the flag. A writer fills two fields inside synchronized (lock) and leaves the block; a reader enters the same block. The unlock is the edge: it publishes everything the writer did before it, and the lock acquires that visibility.
Two differences are worth naming. The edge lives on the monitor rather than on a field, so one unlock can publish changes to any number of fields. And the same lock supplies mutual exclusion, which a volatile flag never did.
The failure mode has the same shape as a missing volatile edge: the guarantee exists only between locks of the same monitor object. Two threads that synchronize on different objects have no edge between them at all, which is the trap in the callout below.
static final Object lock = new Object(); static int count; static String label; // writer synchronized (lock) { count = 7; // both writes sit inside the guarded block label = "seven"; } // unlock: publishes both // reader synchronized (lock) { System.out.println(count + " " + label); // must print "7 seven" }
Unlock publishes everything the thread did before it; a later lock on the same monitor acquires that visibility. Same monitor, or no edge.
No chain, no guarantee: what a data race is
The definition is short and worth learning word for word. A data race exists when two accesses to the same variable are conflicting, meaning at least one of them is a write, and they are not ordered by happens-before. Timing appears nowhere in that sentence.
A race is a permission rather than a symptom. Where no chain orders the accesses, the JMM makes no visibility promise at all: a reader may observe a value that was never written, in theory, or a value from an old execution. In practice the symptom is a stale read or a lost update, and on strong hardware the correct answer often appears anyway, which is the part that misleads.
The headline guarantee is quotable, and worth memorizing because interviewers ask for it: a program is correctly synchronized when all of its sequentially consistent executions are free of data races, and a correctly synchronized program is guaranteed to appear sequentially consistent. That one sentence is why removing the race beats adding a fence and hoping.
No chain, no guarantee: that is what a data race means.
Happens-before checker · draw the chain
pick a scenario, then read the edges it createsT1 · writer
data = 42;
ready = true;
T2 · reader
while (!ready) { }
use(data);
edges found
program order data = 42 -> ready = true, inside T1
program order while (!ready) -> use(data), inside T2
nothing crosses no volatile access, no monitor, no start, no join
no guaranteethe chain is broken
No chain connects the writer to the reader. The spin loop may never exit, and use(data) may read 0: this program has a data race on both fields.
The roach motel: fences are one-way
One property of the relation explains why some reorderings stay legal even around synchronization, and it has a memorable name. Synchronization is a roach motel: an operation can be moved into a synchronized region, but not out of it. What you write before an unlock stays before that unlock as far as other threads are concerned.
Worked through: a write that appears after a block may be moved into it, because it only gains ordering; a write inside the block may never be moved after the unlock, because the unlock is the thing that publishes it. The same logic runs in reverse at the entry, where a read inside the block may not be hoisted before the lock, since it would then miss the visibility the lock promised.
The practical consequence is the licence the compiler keeps. Because nothing outside may be pulled out, you can reason about a guarded region as one ordered unit: enter, touch what the lock protects, leave. Because things may be pulled in, you cannot reason about the exact instant a fence sits, only about the order it guarantees.
Reads and writes may check into a synchronized block and never check out. That one-way door is the whole publishing story behind every unlock.
Using the relation on purpose
The relation is a checklist in disguise: list the actions that need an order, then pick the primitive that draws the edge between them.
- Write down the two actions that must be ordered: the write of the data, and the read that has to see it.
- Find a primitive both sides already share: a volatile field, a monitor, a thread start or join, or an interrupt when the reader is blocked rather than spinning.
- Draw the chain link by link, naming the rule behind each edge. One missing link (different monitors, the wrong field, a plain access) means there is no chain and no guarantee.
- Respect the direction of the hand-off: write the data first and the flag second, then read the flag first and the data second. Reversing either pair empties the chain.
- Prefer the primitive that also covers the other failures where it applies: a monitor orders and excludes, while a volatile field only orders.
- Same monitor: the unlock and the lock must be on the same object, or no edge exists.
- Same field: the volatile write and the volatile read must be of the same field; a volatile neighbour orders nothing.
- Both sides ordered: a volatile write with a plain read on the other side is not a chain.
- join before reading results: everything the finished thread wrote is visible after the join returns, and nothing is promised before it.
If the chain is not written down, it is not a chain. It is two threads that happened to run in the right order when you tested.
The edge on the wrong object
Two threads, both using `synchronized`, and no visibility between them: they lock different objects, so no unlock ever happens-before a lock and no chain exists. The same failure has four disguises worth knowing by name. A lock object created fresh inside the method, so every caller gets a monitor of its own. A volatile write on field A with a plain read of field B, where only A was ordered. A reader that checks an ordered flag and then reads the data through a field nobody ordered. And a join that was never called, so results are read before the thread that produced them has finished. In every case the repair completes the chain; adding more synchronization on the side does not.
Interview angles
What does happens-before actually guarantee?+
Two things: everything the first action did is visible to the second, and the second appears to occur after the first. It is a partial order over actions, so two actions without a chain have no order at all, and it says nothing about wall-clock time.
List the ways one thread can be ordered against another.+
Program order inside a thread; a monitor unlock before a later lock of the same monitor; a volatile write before a later read of the same field; start() before the new thread's first action; every action of a thread before another thread returns from join on it; an interrupt before its detection; the default writes before any action; and transitivity, which chains any of those.
Follow-up: Which of those would you use to hand one value from a worker back to main?
What is a data race, precisely?+
Two conflicting accesses to the same variable that are not ordered by happens-before, where conflicting means at least one is a write. The definition mentions ordering only, which is why 'they never run at the same time' is not a defence.
Do two unsynchronized threads have to see each other's writes eventually?+
No. Without a chain the JMM makes no visibility promise, so a plain read may return an old value indefinitely. Volatile reads are different in kind: the volatile accesses to a field form a single total order, so once the writer's write is in that order, later volatile reads of the field must observe that write or a later one.
Does a volatile write publish everything the thread did before it?+
Yes, once a reader observes that write through a volatile read, transitivity chains every earlier action in the writer to every later action in the reader. Anything the writer does after the volatile write is not published by it.
What does the roach motel say, and why does it matter in review?+
Operations may move into a synchronized region but never out of it, so the unlock stays the final word for everything before it. In review that means you can treat a guarded region as one ordered unit, and that nothing guarded can be observed after the lock was released.