Happens-before in plain words
35 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Happens-before is the rule in the Java Memory Model that decides what one thread is guaranteed to see. If action A happens-before action B, then B sees A's writes, and every write that came before A. If no rule connects two actions in different threads, Java promises nothing.
Program order inside one thread
Happens-before is the Java rule that guarantees one action's results are visible to another, for example everything before unlocking a lock is visible after locking it.
The program order rule: inside one thread, each action happens-before every action that comes later in the code. So a thread always sees its own writes. The CPU may still reorder work behind the scenes, but never in a way that thread can notice.
// Inside ONE threadint marks = 87; // AString grade = "A"; // B A happens-before BSystem.out.println(marks); // C sees 87 (A happens-before C)
// Thread 1 // Thread 2data = 42; while (!ready) { }ready = true; print(data); // plain fields: may print 0Happens-before is also transitive: if A happens-before B and B happens-before C, then A happens-before C. Every rule below links one thread to another; program order and transitivity carry the guarantee along each thread.
Program order alone says nothing to other threads. Another thread may see ready as true and data still as 0 unless some rule connects them.
Unlock before a later lock of the same monitor
The monitor lock rule: unlocking a monitor happens-before every later lock of the same monitor. A monitor is the lock built into every Java object; synchronized takes and releases it.
Example 1 · Monitor lock rule: publish a result under a lock
class ResultBoard { private String topper; // plain fields private int marks; private boolean published;
synchronized void publish(String name, int m) { topper = name; marks = m; published = true; } // unlock: everything above is "released"
synchronized String readIfPublished() { // lock: sees what the last unlock released if (!published) { return null; } return topper + " scored " + marks; }}
public class LockRuleDemo { public static void main(String[] args) throws InterruptedException { ResultBoard board = new ResultBoard();
Thread reader = new Thread(() -> { String line; while ((line = board.readIfPublished()) == null) { Thread.onSpinWait(); } System.out.println("reader: " + line); }, "reader"); reader.start();
Thread.sleep(30); System.out.println("admin: publishing the topper"); board.publish("Meera Iyer", 498); reader.join(); }}admin: publishing the topper reader: Meera Iyer scored 498
What this code does
topper,marksandpublishedare plain fields.publishwrites them insidesynchronized, andreadIfPublishedreads them insidesynchronizedon the sameboard, so the unlock-then-lock chain makes all three visible together.- The reader never sees
publishedastruewith an old name or old marks, because it cannot even look until the writer has left the lock.
So everything a thread wrote before leaving a synchronized block is visible to the next thread that enters a synchronized block on the same object. The fields themselves can be plain. Two different lock objects give no promise at all.
volatile write before a later read
The volatile rule: a write to a volatile field happens-before every later read of that field that sees the written value.
Example 2 · Volatile rule: plain data published by one volatile flag
class FoodOrder { String item; int amount; String address; volatile boolean ready;}
public class VolatilePublishDemo { public static void main(String[] args) throws InterruptedException { FoodOrder order = new FoodOrder();
Thread rider = new Thread(() -> { while (!order.ready) { // C: volatile read Thread.onSpinWait(); } System.out.println("rider: " + order.item + ", Rs " + order.amount + ", to " + order.address); }, "rider"); rider.start();
Thread.sleep(30); System.out.println("app: packing the order"); order.item = "Wireless Mouse"; // A: plain writes order.amount = 120; order.address = "Hostel B, Room 214"; order.ready = true; // B: volatile write, last rider.join(); System.out.println("app: delivered"); }}app: packing the order rider: Wireless Mouse, Rs 120, to Hostel B, Room 214 app: delivered
What this code does
- Only
readyis volatile. The three plain writes (A) come before the volatile write (B), and the rider reads the plain fields (D, theprintlnof the three fields) after it seesready(C), so the chain A → B → C → D holds. - The rider can print only after
readybecomestrue, and main printsdeliveredonly afterjoin(), so the order of the lines is fixed.
Example 3 · Mistake: the flag is written before the data
class FoodOrder { String item; int amount; volatile boolean ready;}
public class FlagFirstMistakeDemo { public static void main(String[] args) throws InterruptedException { FoodOrder order = new FoodOrder();
Thread rider = new Thread(() -> { while (!order.ready) { Thread.onSpinWait(); } System.out.println("rider: " + order.item + ", Rs " + order.amount); }, "rider"); rider.start();
Thread.sleep(30); order.ready = true; // wrong: the flag goes first Thread.sleep(50); // makes the gap easy to see order.item = "Wireless Mouse"; order.amount = 120; rider.join(); System.out.println("app: wrote the order details too late"); }}rider: null, Rs 0 app: wrote the order details too late
What this code does
- The volatile write now comes first, so the rider wakes up before the order exists and prints
nulland 0. The sleep only makes the gap wide enough to see every time. - Without the sleep the gap is tiny and the bug would show only now and then, which is worse. The fix is to move
order.ready = trueto the end.
The order matters. If the writer sets the flag first and the data afterwards, the data writes come after the volatile write, so no rule covers them. The reader may see the flag and old data.
Add program order on both sides and you get the most useful pattern in Java: write plain data first, then a volatile flag; a reader that sees the flag also sees the data.
Order of execution
Build the safe order
Put the steps in the order that guarantees the reader sees the item.
Thread start() and join() rules
The start rule: a call to t.start() happens-before every action in thread t. Anything you set up before start() (plain fields, plain lists) is visible inside the new thread.
Example 4 · Start and join rules: no locks needed
import java.util.ArrayList;import java.util.List;
public class StartJoinDemo { static List<Integer> marks = new ArrayList<>(); // plain, not thread-safe static int highest; static double average;
public static void main(String[] args) throws InterruptedException { marks.add(72); marks.add(95); marks.add(64); marks.add(88);
Thread stats = new Thread(() -> { int sum = 0; for (int m : marks) { // start rule: sees all four marks sum += m; highest = Math.max(highest, m); } average = sum / (double) marks.size(); }, "stats");
stats.start(); stats.join(); // join rule: sees highest and average
System.out.println("Highest: " + highest); System.out.println("Average: " + average); }}Highest: 95 Average: 79.75
What this code does
- The marks were added before
stats.start(), so the start rule guarantees the thread sees all four, even thoughArrayListis not thread-safe. highestandaverageare plain fields written by the thread. Afterjoin()returns, the join rule guarantees main sees the final values.
- Writes made after
start()are not covered by the start rule. - Other rules exist:
interrupt()before the interrupted thread notices it,finalfields (next lesson), and the thread-safe classes ofjava.util.concurrent(later modules).
The join rule: every action in thread t happens-before another thread returns from t.join(). The same holds when t.isAlive() returns false. That is why results written by a worker can be read safely after join() with no lock.
Proving that a read is safe
Proving visibility means finding a chain of rules from the write to the read. Label the write and the read, then connect them using only program order, transitivity and one cross-thread rule per hop.
// Writer thread // Reader threadorder.item = "Mouse"; // A while (!order.ready) { } // C (sees true)order.ready = true; // B print(order.item); // D
// A -> B program order (writer)// B -> C volatile rule (C saw B's value)// C -> D program order (reader)// So A happens-before D: D prints "Mouse".If you find a chain, the read is guaranteed to see the write on every JVM and CPU. If you cannot find one, the program has a data race (two threads touch the same field, at least one writes, and no happens-before connects them), and "it works when I test it" proves nothing.
Next step
Check your understanding
12 quick questions