Introduction
The happens before relationship java is formalised in JSR-133 (Java 5, September 2004), drawing on Leslie Lamport's seminal 1978 paper "Time, Clocks, and the Ordering of Events in a Distributed System" which introduced the happens-before concept for distributed systems. The Java Memory Model adapted Lamport's relation to single-JVM multithreading and defined eight specific rules under which one action is guaranteed to be visible to another. Without these rules, the JVM, the JIT, and the CPU would be free to reorder reads and writes for performance, and concurrent programs would be unprovable.
For a Java learner, the happens before relationship java is the single most important concept to internalise before writing non-trivial concurrent code. It is the difference between writing private static volatile boolean stop = false; and watching your thread terminate cleanly versus writing private static boolean stop = false; and watching it loop forever. The happens-before relation gives you a mental model that answers two questions: which thread's writes am I guaranteed to see, and which of my writes am I guaranteed to publish? This post walks through all eight rules with a runnable program that exercises each one.
What is the Happens Before Relationship in Java?
The happens before relationship in Java is a partial order on actions (reads, writes, lock acquisitions, lock releases, thread starts, thread joins) that the JMM uses to define memory visibility. If action A happens-before action B, then the memory effects of A are visible to B -- specifically, every write that happened before A in program order is visible to every read that happens after B. The relation is transitive: if A happens-before B and B happens-before C, then A happens-before C. It is a partial order because most pairs of actions in different threads have no happens-before edge between them, and that is exactly the situation called a data race.
The JMM defines happens-before through eight rules: (1) program order rule -- each action in a thread happens-before every subsequent action in that thread; (2) monitor lock rule -- an unlock on a monitor happens-before every subsequent lock on the same monitor; (3) volatile variable rule -- a write to a volatile field happens-before every subsequent read of the same field; (4) thread start rule -- a call to Thread.start() happens-before the first action of the started thread; (5) thread termination rule -- the last action in a thread happens-before any other thread detecting that the thread has terminated (via Thread.join() or Thread.isAlive() returning false); (6) thread interruption rule -- a thread calling Thread.interrupt() happens-before the interrupted thread detecting the interrupt; (7) object finalizer rule -- the end of a constructor happens-before the start of the finalizer for that object; (8) transitivity rule.
How the Happens Before Relationship Works - Step by Step
Step 1: Program order rule. Within a single thread, every action happens-before every action that textually follows it. This is what lets you write int x = compute(); int y = x + 1; and know that y uses the value of x you just computed. Note that program order does NOT cross threads: the JIT is free to reorder actions within a thread as long as the reordering preserves the intra-thread semantics, and only the JMM rules give cross-thread visibility.
Step 2: Volatile variable rule. If thread A writes a volatile field and thread B later reads the same volatile field, the write happens-before the read, and as a side effect every write that happened-before the volatile write in A is also visible to every read that happens-after the volatile read in B. This is how a volatile boolean ready flag publishes a nonVolatile int data field: as long as the writer sets data before ready, the reader that observes ready == true is guaranteed to see the latest data.
Step 3: Monitor lock rule. If thread A releases a lock and thread B later acquires the same lock, the release happens-before the acquire. This is why a synchronized block is both a mutex and a memory barrier: every write inside the synchronized block in A is published before A releases the lock, and every read inside the synchronized block in B sees those writes because B's acquire acts as an acquire barrier.
Step 4: Thread start rule. A call to Thread.start() happens-before the first action of the started thread. This means any writes the parent thread did before calling start() are visible to the started thread, even without synchronisation. This is how you can pass arguments to a Runnable that uses non-final fields and still see them set correctly: the start() call publishes them.
Step 5: Thread termination rule. The last action in a thread happens-before any action in another thread that detects the termination, which in practice means Thread.join() returns or Thread.isAlive() returns false. So when you call t.join() and it returns, you are guaranteed to see every write that t made before it terminated. This is the easiest way to wait for a worker thread to finish and read its results without volatile fields or atomics.
Step 6: Thread interruption and finalizer rules. A call to Thread.interrupt() happens-before the interrupted thread observes the interrupt (via InterruptedException or Thread.interrupted()). The end of a constructor happens-before the start of the finalizer. These two rules are less commonly exercised in everyday code but they close the formal model so that the JMM has no gaps.
Step 7: Transitivity rule. If A happens-before B and B happens-before C, then A happens-before C. This is what chains the rules together: a thread that writes data, then writes a volatile flag, then joins another thread that reads the volatile flag and writes a result, gives the original thread visibility of that result through the chain.
Java Program for the Happens Before Relationship
import java.util.concurrent.atomic.AtomicInteger;
public class HappensBeforeDemo {
private static volatile boolean ready = false;
private static int number = 0;
private static int counter = 0;
public static void main(String[] args) throws Exception {
// --- Program Order Rule ---
System.out.println("--- Program Order Rule ---");
number = 1; // (A)
counter = number + 1; // (B) sees A due to program order
System.out.println("counter = " + counter);
// --- Volatile Variable Rule ---
System.out.println("--- Volatile Variable Rule ---");
Thread writer = new Thread(() -> {
number = 42;
ready = true; // volatile write publishes number
});
Thread reader = new Thread(() -> {
while (!ready) { Thread.yield(); }
// Sees number = 42 because ready write HB ready read
System.out.println("Reader saw number = " + number);
});
reader.start();
writer.start();
reader.join();
writer.join();
// --- Monitor Lock Rule ---
System.out.println("--- Monitor Lock Rule ---");
final Object lock = new Object();
final int[] shared = new int[]{0};
Thread t1 = new Thread(() -> {
synchronized (lock) { shared[0] = 100; }
});
t1.start();
t1.join();
Thread t2 = new Thread(() -> {
synchronized (lock) {
System.out.println("shared[0] = " + shared[0]);
}
});
t2.start();
t2.join();
// --- Thread Start Rule ---
System.out.println("--- Thread Start Rule ---");
number = 77;
Thread t3 = new Thread(() -> {
// Sees number = 77 because start() happens-before first action
System.out.println("Thread started, sees number = " + number);
});
t3.start();
t3.join();
// --- Thread Termination Rule ---
System.out.println("--- Thread Termination Rule ---");
final int[] result = new int[]{0};
Thread t4 = new Thread(() -> { result[0] = 99; });
t4.start();
t4.join();
// t4's writes HB t4.join() return
System.out.println("result after join = " + result[0]);
// --- Final Field Rule (safe publication) ---
System.out.println("--- Final Field Rule ---");
class Box {
final int v;
Box(int v) { this.v = v; }
}
Box b = new Box(55);
System.out.println("Box.v = " + b.v);
System.out.println("All happens-before rules demonstrated.");
}
}
Code Explanation - Line by Line
The first block exercises the program order rule. Statement (A) writes 1 to number, and statement (B) reads number and adds 1 to set counter. Because both are in the same thread and (A) textually precedes (B), the JMM guarantees that (B) sees the value 1 that (A) wrote, so counter is 2. This is the simplest possible happens-before edge, but it is the foundation on which all the other rules build.
The second block exercises the volatile variable rule. The writer thread writes 42 to a non-volatile field number, then writes true to the volatile field ready. The reader thread yields in a tight loop until ready becomes true, then prints number. The volatile write happens-before the volatile read, and transitivity plus program order means the write of 42 to number is visible to the reader. Without volatile, the JIT could hoist the read of ready out of the loop and the reader would spin forever.
The third block exercises the monitor lock rule. Thread t1 acquires the lock, writes 100 to the shared array, and releases. Thread t2 later acquires the same lock and reads the value. The release in t1 happens-before the acquire in t2, so t2 is guaranteed to see 100. Without synchronisation, t2 might see 0.
The fourth block exercises the thread start rule. The main thread writes 77 to number, then calls t3.start(). The start() call happens-before the first action of t3, so t3's println sees 77. Note that this rule only applies to writes that happened before start(); writes that happen after start() in the main thread are not guaranteed visible without further synchronisation.
The fifth block exercises the thread termination rule. Thread t4 writes 99 to the result array. The main thread calls t4.join() which blocks until t4 terminates. The last action of t4 happens-before the join() returns, so the main thread is guaranteed to see result[0] == 99. This is the easiest way to harvest a worker thread's output.
The sixth block exercises the final field rule by declaring a local class Box with a final field v. The constructor sets v to 55, and the JIT inserts a memory barrier at the end of the constructor so the value is published safely. The println sees 55 without any synchronisation because of the safe publication guarantee that final fields enjoy.
Interview Questions and Answers
Q1. What is the happens-before relationship in Java?
The happens-before relationship is a partial order on memory actions defined by the Java Memory Model (JSR-133). If action A happens-before action B, then the memory effects of A (every write A made or that happened-before A) are visible to B. The JMM specifies eight rules that create happens-before edges: program order, monitor lock, volatile variable, thread start, thread termination, thread interruption, object finalizer, and transitivity.
Q2. What is the difference between happens-before and program order?
Program order is the textual order of statements within a single thread -- it is intra-thread. Happens-before is a cross-thread relation that the JMM defines through eight rules, of which program order is one. Program order alone gives no visibility across threads: a write in thread A is not visible to a read in thread B unless there is a happens-before edge connecting them (a volatile, a lock, a thread start, etc.). Without such an edge you have a data race and the JMM gives no guarantees.
Q3. How does volatile create a happens-before edge?
A write to a volatile field happens-before every subsequent read of the same field. The "subsequent" here means a read that observes the write, defined more carefully in the JMM as a read that sees a value that was written. The volatile rule also has a transitively-publishing effect: every write that happened-before the volatile write in the writer thread becomes visible to every read that happens-after the volatile read in the reader thread. This is why a volatile boolean flag can safely publish a non-volatile data field.
Q4. What does Thread.start() guarantee about visibility?
The thread start rule says that the call to Thread.start() happens-before the first action of the started thread. In practical terms, any write the parent thread did before calling start() is guaranteed visible to the new thread -- even on non-final fields without volatile. However, writes that happen after start() in the parent thread are not automatically visible; you need another happens-before edge (volatile, lock, atomic) for those.
Q5. What does Thread.join() guarantee about visibility?
The thread termination rule says that the last action in a thread happens-before any action in another thread that detects the termination, which in practice is the return of Thread.join() or Thread.isAlive() returning false. So when join() returns, the joining thread is guaranteed to see every write the joined thread made before it terminated. This is why join() is the easiest way to harvest a worker thread's output without volatile fields.
Q6. Is the synchronized block a memory barrier?
Yes. The monitor lock rule says that an unlock on a monitor happens-before every subsequent lock on the same monitor. This has two effects: mutual exclusion (only one thread holds the lock at a time) and memory visibility (writes inside the synchronized block are flushed to main memory on unlock, reads inside the block are refreshed from main memory on lock). Without the memory visibility half, synchronized would be a mutex but not a memory barrier, and you would need separate volatile fields for visibility.
Q7. In a producer-consumer pattern, the producer puts a non-volatile Object into a queue and increments a volatile long counter; the consumer reads the counter and then polls the queue. Is the consumer guaranteed to see the object the producer put?
Yes. The producer's writes happen-before its volatile counter increment (program order). The volatile counter increment happens-before the consumer's read of the counter (volatile rule). The consumer's read of the counter happens-before its poll of the queue (program order). By transitivity, the producer's writes to the object happen-before the consumer's poll of the queue, so the consumer is guaranteed to see the fully-constructed object. This is how java.util.concurrent.ArrayBlockingQueue publishes elements without volatile fields on the elements themselves.
Sample Input and Output
Input: Run HappensBeforeDemo on a multi-core JVM. Output: --- Program Order Rule --- counter = 2 --- Volatile Variable Rule --- Reader saw number = 42 --- Monitor Lock Rule --- shared[0] = 100 --- Thread Start Rule --- Thread started, sees number = 77 --- Thread Termination Rule --- result after join = 99 --- Final Field Rule --- Box.v = 55 All happens-before rules demonstrated.
The output shows that every happens-before rule produces the expected visible value: counter is 2, the reader sees the published 42, the lock-protected shared array shows 100, the started thread sees the 77 written before start(), the joined thread's 99 is visible, and the final Box field is 55. These are all guarantees of the JMM, not coincidences -- the JVM is required to produce them on every compliant JVM.
Common Mistakes to Avoid
First, do not assume that statements that are textually adjacent in different threads have any ordering between them. Without a happens-before edge, the JIT and the CPU are free to reorder across threads. Second, do not assume that calling a setter on an object in thread A makes the new value visible to thread B -- you need a volatile field, a lock, an atomic, or a thread start/join to create the edge. Third, do not use a non-final mutable field for publication; the reader could see the field's default value (0, false, null) forever without an edge.
Fourth, do not rely on object construction for visibility without final. A non-final field set in the constructor could be reordered with the object reference publication, so a thread that races to read it could see the default value. Mark the field final or use a synchronized block to publish. Finally, do not chain happens-before edges incorrectly -- transitivity requires all the intermediate edges to be present, so a missing edge breaks the chain and the JMM gives no guarantees about what the reader sees.
Real-World Applications
The happens before relationship java underpins every concurrent data structure in the JDK. java.util.concurrent.ConcurrentHashMap uses volatile reads of the bucket array and the per-segment counter to provide lock-free reads. java.util.concurrent.atomic.AtomicInteger and the rest of the atomic family piggyback on the volatile happens-before edge. java.util.concurrent.ArrayBlockingQueue uses a single ReentrantLock for both put and take, which gives a happens-before edge between every producer and consumer. java.util.concurrent.FutureTask uses a volatile state field to publish the result of the computation.
Beyond the JDK, the happens-before model is used by Spring's singleton bean factory (publishes beans via the thread start rule when the bean is created by a worker thread), by Hibernate's session cache (publishes loaded entities via the lock on the session), and by Android's Handler and Looper (publishes messages via the lock on the message queue). Reactive Streams backpressure uses a volatile long field for the demand counter. Anywhere two threads share data, the happens-before relation is what makes the sharing correct.
Conclusion
The happens before relationship java is the formal ordering relation that the JMM uses to define memory visibility across threads. Eight rules -- program order, monitor lock, volatile variable, thread start, thread termination, interruption, finalizer, and transitivity -- combine to give programmers a mental model for when one thread is guaranteed to see another thread's writes. Mastering these rules lets you write lock-free and wait-free code that is still provably correct. Next, study the java.util.concurrent package, Brian Goetz's Java Concurrency in Practice, and the source of AbstractQueuedSynchronizer.
Comments
Comments
Post a Comment