Sub topic 15
The Java Memory Model and Happens-Before
In earlier chapters you met several tools: synchronized, volatile, Thread.start(), and join(). Each one fixed a visibility problem, where one thread could not see another thread's write. This chapter explains the single rule that sits behind all of them: the happens-before relationship.
What the Java Memory Model Is
The Java Memory Model (JMM) is the part of the Java language rules that says when a write made by one thread must be visible to a read made by another thread.
Without these rules, a program could not count on anything. The compiler, the JVM, and the CPU are all allowed to speed up your code. Here are two things they may do:
- Reordering means running instructions in a different order than you wrote them, as long as a single thread cannot tell the difference.
- Caching means a CPU core keeps a value in its own fast memory instead of writing it to main memory right away.
On one thread, these tricks never change your results. Across threads, they can. Another thread may see writes late, out of order, or never.
The JMM does not list every possible trick. It gives you one guarantee you can rely on instead.
The Happens-Before Rule
Happens-before is a relationship between two actions, such as a write and a read. If action A happens-before action B, then:
- Everything A did is visible to B.
- A appears to B as if it ran first.
If there is no happens-before relationship between a write and a read in different threads, the read may see the old value, the new value, or a mix of both. That situation is called a data race.
The Rules That Create Happens-Before
Java creates happens-before relationships only in specific situations. These are the main ones:
| Rule | What it says |
|---|---|
| Program order | Within one thread, each action happens-before every later action in that thread. |
| Monitor lock | Unlocking a lock happens-before every later locking of the **same** lock. |
| Volatile variable | A write to a volatile field happens-before every later read of that **same** field. |
| Thread start | A call to `t.start()` happens-before every action inside thread `t`. |
| Thread join | Every action in thread `t` happens-before another thread returns from `t.join()`. |
| Transitivity | If A happens-before B, and B happens-before C, then A happens-before C. |
The last rule, transitivity, matters a lot. It lets one synchronizing action make many plain writes visible.
Worked Example: Start and Join
Here is a program with no synchronized and no volatile that is still correct.
public class StartJoinDemo {
private static int result = 0; // plain field
private static int input = 0; // plain field
public static void main(String[] args) throws InterruptedException {
input = 21; // (1) main writes input
Thread worker = new Thread(() -> {
result = input * 2; // (3) worker reads input, writes result
});
worker.start(); // (2) start
worker.join(); // (4) join
System.out.println(result); // (5) always prints 42
}
}Here is why it is safe:
- Step (1) happens-before (2) by program order.
- Step (2) happens-before (3) by the thread start rule. So the worker sees
input = 21. - Step (3) happens-before the return from (4) by the thread join rule.
- Step (4) happens-before (5) by program order. So main sees
result = 42.
Each link in the chain is backed by a rule from the table.
Worked Example: Publishing Data With a Volatile Flag
Transitivity lets a single volatile field protect plain fields that are written before it.
public class Publisher {
private static int answer = 0; // plain field
private static String message = null; // plain field
private static volatile boolean ready = false;
public static void main(String[] args) throws InterruptedException {
Thread reader = new Thread(() -> {
while (!ready) {
Thread.onSpinWait(); // wait until ready
}
// Guaranteed to see both plain writes below
System.out.println(message + " " + answer);
});
reader.start();
answer = 42; // (A) plain write
message = "The answer is"; // (B) plain write
ready = true; // (C) volatile write
reader.join();
}
}The reader always prints The answer is 42. Here is the chain:
- (A) and (B) happen-before (C) by program order.
- (C) happens-before the reader's read of
readythat returnstrue, by the volatile rule. - By transitivity, (A) and (B) happen-before the reader's print.
How Locks Fit the Same Model
The monitor lock rule works the same way as the volatile rule. When a thread leaves a synchronized block, it unlocks the lock. When another thread later enters a block on the same lock, it sees everything the first thread did before unlocking.
public class SharedBox {
private final Object lock = new Object();
private int value; // plain field, guarded by lock
public void set(int v) {
synchronized (lock) { // unlock at end happens-before next lock
value = v;
}
}
public int get() {
synchronized (lock) { // sees writes made before the last unlock
return value;
}
}
}This is why the get() method must also be synchronized. If get() skipped the lock, there would be no happens-before edge, and it could return an old value.
Common Mistakes
- Locking on different objects. The lock rule only links an unlock and a lock of the same lock. Two threads that use two different lock objects get no visibility guarantee.
- Reading a volatile without seeing the write. The volatile rule applies only when the read returns the value written. If the reader never checks the flag, nothing is guaranteed.
- Thinking "it worked on my machine" proves safety. A data race may hide for months on one CPU and fail on another. The rules decide correctness, not test runs.
- Using
Thread.sleep()to wait for a write. Sleeping creates no happens-before edge. It only makes a race less likely to show up.
Exercises
Exercise
Thread 1 runs x = 5; synchronized (lockA) { }. Later, Thread 2 runs synchronized (lockB) { System.out.println(x); }. Is Thread 2 guaranteed to print 5? Why or why not?
Show answer
No. The monitor lock rule only links an unlock and a later lock of the same lock. Thread 1 used lockA and Thread 2 used lockB, so no happens-before edge connects the write to the read. Thread 2 may print 0.
Exercise
In the Publisher example, the main thread writes ready = true first and then answer = 42. The reader waits for ready and then prints answer. What can it print, and why?
Show answer
It may print 0 or 42. The write to answer comes after the volatile write in program order, so no chain of rules connects it to the reader's read. Without a happens-before relationship, the new value is not guaranteed to be visible.
Exercise
A main thread sets a plain field config = "prod", then calls worker.start(). The worker reads config. Does the worker need volatile or synchronized to see "prod"? Name the rules that apply.
Show answer
No. Program order makes the write happen-before start(). The thread start rule makes start() happen-before every action in the worker. By transitivity, the write is visible to the worker.