Skip to content
javahacks.dev
Concurrency

Java Memory Model and Happens Before Explained With Examples

What the Java Memory Model guarantees about visibility and ordering, how happens-before edges are created and why unsynchronized code can loop forever.

8 min read
Summarize in AI
Flat illustration of a heap of objects with the unreachable ones being recycled, with the OpenJDK, Grafana, Linux and Prometheus logos.

Single-threaded Java reads like the code says. Multi-threaded Java does not, and the reason is not a bug in the JVM. Processors keep values in registers and per-core caches, compilers reorder and hoist instructions, and none of that is observable from one thread. The Java Memory Model (JMM), specified in chapter 17 of the language specification, is the contract that says exactly when another thread is allowed, and required, to see your writes. If you know what a happens-before edge is, you can look at a piece of concurrent code and say whether it is correct. If you do not, you are guessing, and the failures show up only on production hardware under load.

This post shows the failure first, with output from a real run, then builds the rules up: happens-before, the edges you get for free, unsafe publication, and what the model leaves unspecified. The examples ran on JDK 17.0.1 on a 10-core ARM laptop, and the rules are unchanged in Java 25.

A loop that never ends

Here is a worker that spins until another thread sets a flag. The main thread waits 200 ms, sets the flag and waits up to two seconds for the worker to finish:

src/main/java/dev/javahacks/jmm/Visibility.javajava
public class Visibility {
    static boolean stop;   // the flag, with no synchronization

    public static void main(String[] args) throws Exception {
        Thread worker = new Thread(() -> {
            long spins = 0;
            while (!stop) {
                spins++;
            }
            System.out.println("worker saw stop after " + spins + " spins");
        });
        worker.start();
        Thread.sleep(200);
        stop = true;
        worker.join(2000);
        System.out.println(worker.isAlive() ? "worker STILL RUNNING" : "worker finished");
        System.exit(0);
    }
}
Text
worker STILL RUNNING

The program never prints "worker saw stop". The worker is alive two seconds after the write. This is not a race that sometimes loses. After the JIT compiler warms the loop it sees that nothing inside it changes stop, so it is allowed to read the field once and turn the loop into while (true). The write in main is real, and the worker will never observe it.

Now change one word, static volatile boolean stop;, and run it again:

Text
worker saw stop after 344077982 spins
worker finished

The spin count differs on every run, which is the point: the exact number is timing, and the guarantee is that it ends. One keyword made the write visible, and the question for the rest of the post is why that keyword works and what else does what it does.

What happens-before means

The JMM is defined in terms of an ordering between actions called happens-before. If action A happens-before action B, two things hold: the effects of A are visible to B, and A is ordered before B as far as B can tell. If no such edge connects two actions, the JVM may reorder them or show a stale value, and any program that depends on one outcome has a data race.

Edges exist only where the specification creates them:

EdgeWhat it connects
Program orderEach action in a thread happens-before the next one in that same thread
Monitor lockAn unlock of a monitor happens-before every later lock of that same monitor
volatileA write to a volatile field happens-before every later read of that same field
Thread startThread.start() happens-before every action in the started thread
Thread endEvery action in a thread happens-before another thread's successful join() on it
final fieldsThe end of a constructor happens-before any thread reads that object's final fields through a reference obtained after construction
java.util.concurrentPutting an element into a queue or submitting a task happens-before the action that takes it or runs it; Future.get() sees the task's effects

Happens-before is transitive. If A happens-before B and B happens-before C, then A happens-before C. That transitivity is what makes one volatile flag enough to publish a whole structure, as the next example shows.

A volatile write publishes everything before it

A volatile variable carries more than its own value. Everything the writing thread did before the write is visible to a thread that reads the new value:

src/main/java/dev/javahacks/jmm/Publish.javajava
public class Publish {
    static int payload;               // plain field
    static volatile boolean ready;    // the edge

    public static void main(String[] args) throws Exception {
        Thread reader = new Thread(() -> {
            while (!ready) { }        // spin until the volatile read sees true
            System.out.println("payload = " + payload);
        });
        reader.start();

        payload = 42;                 // 1. ordinary write
        ready = true;                 // 2. volatile write: publishes step 1
        reader.join();
    }
}
Text
payload = 42

The reader prints 42 and never 0. Program order puts payload = 42 before the volatile write, the volatile write happens-before the volatile read that sees true, and the read happens-before the print. By transitivity the print sees 42. Remove volatile and the output is allowed to be 0, or the program to hang.

Compare this with AtomicBoolean, which gives the same guarantees plus compare-and-set. A volatile field is the right tool when one thread writes and others read. It is the wrong tool for count++, because the increment is three steps (read, add, write) and the edge does not make them one. For that, see volatile vs synchronized vs atomics.

Locks give you the same edge

A synchronized block does the same job for every field you touch inside it, not only one variable:

src/main/java/dev/javahacks/jmm/Counter.javajava
public class Counter {
    private int value;                          // not volatile, and does not need to be

    public synchronized void increment() { value++; }

    public synchronized int get() { return value; }
}

Unlocking after increment() happens-before the next lock in get() on the same object, so a reader sees every completed increment. Two rules fall out of this. Both sides must use the same monitor: a writer that locks this and a reader that locks nothing has no edge. And the guarantee covers the data the lock protects, which is why you keep guarded fields private and touch them only inside the lock.

Unsafe publication

Publication means making an object reachable by another thread. It is safe when the handover passes through an edge, and unsafe when the reference travels through a plain field:

src/main/java/dev/javahacks/jmm/Config.javajava
public class Config {
    private final int timeoutMs;     // final: safe even without other edges
    private int retries;             // not final: needs an edge to be seen

    public Config(int timeoutMs, int retries) {
        this.timeoutMs = timeoutMs;
        this.retries = retries;
    }

    static Config shared;            // unsafe: plain field

    static void publish()  { shared = new Config(500, 3); }
    static Config read()   { return shared; }  // may see null, or retries == 0
}

A thread that calls read() may see null for a while, and, worse, may see a non-null Config whose retries is still 0. The cause is reordering: the reference store to shared can become visible before the stores inside the constructor. The final field is the exception, because the JMM guarantees a properly constructed object's final fields are seen correctly, as long as this did not escape from the constructor.

There are four safe ways to publish, in order of how often you should reach for them:

  1. Hand it through a concurrent collection or queue, such as ConcurrentHashMap or BlockingQueue.
  2. Store the reference in a volatile field, or an AtomicReference.
  3. Store it while holding a lock that readers also take.
  4. Make every field final, and for configuration objects prefer a record, which is immutable by construction.

The cheapest cure is immutability. An object that never changes after construction has nothing to publish and nothing to synchronize.

The edges you get without thinking

You do not hand-write edges for most concurrent code, because the library already did:

src/main/java/dev/javahacks/jmm/Tasks.javajava
import java.util.concurrent.*;

public class Tasks {
    public static void main(String[] args) throws Exception {
        int[] result = new int[1];                       // plain array, plain write
        try (ExecutorService pool = Executors.newFixedThreadPool(2)) {
            Future<?> f = pool.submit(() -> result[0] = 7 * 6);
            f.get();                                     // edge: task effects visible after get()
            System.out.println(result[0]);
        }
    }
}
Text
42

submit() happens-before the task runs, and the task's effects happen-before get() returns. So the plain write inside the task is visible without volatile. The same holds for CountDownLatch.await() after countDown(), for Thread.join(), and for taking from a BlockingQueue what another thread put in it. When you build on these classes and share only through them, you rarely write a volatile yourself. The tour of those classes is in threads, executors and futures.

What the model does not promise

The JMM guarantees visibility and ordering only across edges. It does not give you atomicity of compound actions, so volatile int count; count++ still loses updates. It does not promise fairness, so a thread may starve. It gives long and double atomic reads and writes only when they are volatile, because the specification allows a non-atomic 64-bit access, even though modern 64-bit JVMs do not tear them. And it says nothing about how fast any of this is. A volatile read on x86 is nearly free, a volatile write costs a memory fence, and contended locks cost real time.

Practical rules

  • Prefer not sharing mutable state. Pass messages through queues, or use immutable objects and records.
  • When you must share, name the edge. If you cannot say which of the table's rows connects the writer to the reader, there isn't one.
  • Use one lock for one invariant, and take it for reads as well as writes.
  • Put volatile on a flag or a reference that one thread writes and others read. Do not use it for read-modify-write.
  • Never spin on a plain field. The loop in the first example is not rare; it is what the optimizer is entitled to produce.
  • Test on real cores. A data race that never fires on your laptop with two threads fires on a 64-core server with sixty.

Where this does not apply

If your code is single-threaded, or each thread owns its data and only exchanges results through the classes in java.util.concurrent, the model works for you invisibly. Virtual threads follow exactly the same rules as platform threads, so the edges above apply unchanged, and a map shared between threads belongs in a ConcurrentHashMap. For the model's full definition, read chapter 17 of the Java Language Specification, and for the library guarantees, the [memory consistency properties in java.util.concurrent](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/concurrent/package-summary.html#MemoryVisibility).

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.