Java Memory Model and happens-before
What you will learn
The Java Memory Model (JMM) defines which values a read may observe when threads share data. Happens-before is a guarantee about ordering and visibility, not a promise about wall-clock execution order. Use it to reason about publication and completion.
- Trace start, termination, monitor and volatile happens-before edges.
- Publish a snapshot using a volatile reference or a latch.
- Distinguish allowed outcomes from a sampled execution.
Each example is a complete Main.java file. Use a fresh lab-owned directory: javac --release 21 -proc:none Main.java, then java Main. Only finite reviewed tasks are started. Latches and barriers coordinate workers with explicit deadlines; their full APIs are covered in Chapter 32. The fixture runner also enforces a process deadline.
Publish input with start; retrieve result with join
import java.time.Duration;import java.util.concurrent.*;public class Main { // Only finite tasks and timed coordination are used in these examples. static void finish(Thread thread) throws InterruptedException { try { if (!thread.join(Duration.ofSeconds(3))) { thread.interrupt(); if (!thread.join(Duration.ofSeconds(3))) throw new AssertionError("worker did not stop"); throw new AssertionError("worker timed out"); } } catch (InterruptedException e) { thread.interrupt(); throw e; } } static class Box { int input; int result; } public static void main(String[] args) throws Exception { Box box = new Box(); box.input = 21; Thread worker = new Thread(() -> box.result = box.input * 2); worker.start(); finish(worker); System.out.println(box.result); }}Expected output:
42The input write precedes start; the result write precedes termination. No simultaneous conflicting access occurs outside these ordering edges.
The ordering model
Within a thread, program order contributes happens-before edges. Edges compose transitively: if A precedes B and B precedes C in this relation, A precedes C. A call to start orders earlier actions in the caller before actions in the started thread; successful observation of termination by join orders worker actions before subsequent caller actions. Monitor unlock orders a subsequent lock of the same monitor. A volatile write orders subsequent reads of that same field. These relations constrain observations; they do not prescribe a processor instruction schedule.
Publication diagram
Accessible text diagram: producer fills plain fields → producer releases a synchronization mechanism → consumer acquires the corresponding mechanism → consumer reads fields. For CountDownLatch, actions before countDown happen-before actions after a successful corresponding await. An unsuccessful timed await does not grant that guarantee. A volatile reference can publish a fully constructed immutable snapshot; the consumer must first read that reference and then access its state. Keep mutable shared state guarded after publication. Final fields have additional initialization guarantees when construction is correct; final is not a blanket guarantee for later mutations of referenced objects.
Allowed outcomes and boundaries
A data race is conflicting accesses to shared memory, at least one a write, not ordered by happens-before. Correctly synchronized programs have strong reasoning guarantees; a successful sample from a broken program does not prove its safety. Sleep and yield do not establish memory visibility. A reader racing to observe a newly published volatile reference can legitimately see the initial null or the published value; test both permitted outcomes rather than predicting a specific schedule. Volatile is not a general mutex or atomic read-modify-write operation.
Latch publication of a plain field
import java.time.Duration;import java.util.concurrent.*;public class Main { // Only finite tasks and timed coordination are used in these examples. static void finish(Thread thread) throws InterruptedException { try { if (!thread.join(Duration.ofSeconds(3))) { thread.interrupt(); if (!thread.join(Duration.ofSeconds(3))) throw new AssertionError("worker did not stop"); throw new AssertionError("worker timed out"); } } catch (InterruptedException e) { thread.interrupt(); throw e; } } static void await(CountDownLatch latch) { try { if (!latch.await(3, TimeUnit.SECONDS)) throw new AssertionError("latch timed out"); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new AssertionError("unexpected cancellation", e); } } static class Box { int value; } public static void main(String[] args) throws Exception { Box box = new Box(); CountDownLatch available = new CountDownLatch(1); Thread writer = new Thread(() -> { box.value = 17; available.countDown(); }); writer.start(); try { await(available); System.out.println(box.value); } finally { finish(writer); } }}Expected output:
17The plain field is read only after successful await; the writer’s earlier assignment is visible. The join also ensures cleanup.
Publish an immutable volatile snapshot
import java.time.Duration;import java.util.concurrent.*;public class Main { // Only finite tasks and timed coordination are used in these examples. static void finish(Thread thread) throws InterruptedException { try { if (!thread.join(Duration.ofSeconds(3))) { thread.interrupt(); if (!thread.join(Duration.ofSeconds(3))) throw new AssertionError("worker did not stop"); throw new AssertionError("worker timed out"); } } catch (InterruptedException e) { thread.interrupt(); throw e; } } static void meet(CyclicBarrier barrier) { try { barrier.await(3, TimeUnit.SECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new AssertionError("unexpected cancellation", e); } catch (BrokenBarrierException | TimeoutException e) { throw new AssertionError(e); } } record Snapshot(String sku, int stock) {} static class Holder { volatile Snapshot current; } public static void main(String[] args) throws Exception { Holder holder = new Holder(); CyclicBarrier start = new CyclicBarrier(2); Thread writer = new Thread(() -> { meet(start); holder.current = new Snapshot("PEN", 42); }); Thread reader = new Thread(() -> { meet(start); Snapshot observed = holder.current; if (observed != null && (!observed.sku().equals("PEN") || observed.stock() != 42)) throw new AssertionError("invalid snapshot"); System.out.println("allowed observation"); }); writer.start(); reader.start(); try { finish(writer); } finally { finish(reader); } System.out.println(holder.current.stock()); }}Expected output:
allowed observation42The reader may see null or the complete record; the test deliberately normalizes both legal observations. The main thread sees the final snapshot after the writer terminates.
Common mistakes
Do not use a delay to publish a field, assume a failed timed await establishes visibility, or read a volatile reference twice when you need one consistent snapshot. Copy it to a local variable and make the value object immutable.
Practice
Have a worker publish a plain text field using a CountDownLatch. Read it after successful timed await, and always join the writer.
Expected output:
readyCompare your answer with the manual practice criteria.
Official reading: JLS 17 · Thread · CountDownLatch · CyclicBarrier. Java 25 execution remains unverified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Java Memory Model and happens-before — knowledge check
Original concurrency questions. Java 21-compatible scope.
Which action publishes earlier caller writes to a new thread?
What follows a successful corresponding latch await?
What does a volatile snapshot reader guarantee?
Does a timed-out await publish data?
What proves a racy program safe?