The Java Memory Model

The Java Memory Model (JMM) decides when a value written by one thread becomes visible to another, and in what order. Without the right synchronization a thread may never see a change, or see changes in an order nobody wrote. This page reproduces each failure with a program you can run, explains the happens-before rules that prevent them, and measures what the fixes cost.

Share

Contents

Why Java needs a memory model

Single-threaded code behaves as if every statement runs in order and every write goes straight to memory. Underneath, almost nothing works that way. The javac compiler, the JIT compiler and the CPU all reorder, merge and remove memory operations whenever the result looks the same to the thread doing them:

  • The JIT keeps values in registers. A loop that reads a field may read it once before the loop and never again.
  • Each CPU core writes into a store buffer first, and the write reaches the shared cache later. Meanwhile the core carries on, so a later read can complete before an earlier write is visible to other cores.
  • Instructions that do not depend on each other can execute in a different order from the source code.

These optimizations are a large part of why Java is fast, and a single thread can never notice them. A second thread can. The Java Memory Model, chapter 17 of the Java Language Specification, defines exactly what one thread is guaranteed to see of another thread's actions. The current model came from JSR-133 and has been in force since Java 5. Its short version: if two threads use the same variable and at least one of them writes it, the accesses must be connected by a happens-before relation, or the reader may see stale or out-of-order values.

A data race can break three different properties, and the tools differ in which ones they repair:

Synchronization tools and the guarantees they give
ToolSinceVisibilityOrderingAtomic read-modify-writeBest for
volatile fieldJava 1.0 (strengthened in Java 5)YesYesNoFlags and published references
synchronizedJava 1.0YesYesYes, inside the blockUpdating several fields together
final fieldJava 5 semanticsAfter constructionYesNot applicableImmutable objects
Atomic classesJava 5YesYesYes, one variableCounters, single-value state
VarHandle access modesJava 9Depends on modeDepends on modeYes (CAS, getAndAdd)Library code needing weaker, cheaper modes
java.util.concurrent classesJava 5Yes, documented per classYesPer classMost application code

Every program below shows one failure next to the fix. Failures of the memory model depend on timing, the JIT and the CPU, so where a number varies from run to run the text says so. The results were produced with JDK 21 on a 2-CPU x86-64 Linux machine.

Visibility: a write that is never seen

Two threads spin until a flag becomes true. The two flags are identical except that one is volatile. main sets both after half a second, long enough for the JIT to compile the loops, and then waits up to two seconds for each reader to notice.

Java
public class Visibility {

    static boolean plainStop;              // no visibility guarantee
    static volatile boolean volatileStop;  // every write is visible to later reads

    public static void main(String[] args) throws InterruptedException {
        Thread plain = new Thread(() -> {
            long spins = 0;
            while (!plainStop) {           // the JIT may read the field once and never again
                spins++;
            }
            System.out.println("plain reader stopped after " + spins + " spins");
        });
        plain.setDaemon(true);             // so a stuck thread cannot keep the JVM alive

        Thread vol = new Thread(() -> {
            long spins = 0;
            while (!volatileStop) {
                spins++;
            }
            System.out.println("volatile reader stopped");
        });

        plain.start();
        vol.start();
        Thread.sleep(500);                 // let both loops get compiled and hot

        plainStop = true;
        volatileStop = true;

        vol.join(2000);
        plain.join(2000);
        System.out.println("volatile reader alive after 2 s: " + vol.isAlive());
        System.out.println("plain reader alive after 2 s:    " + plain.isAlive());
    }
}

Output (typical on HotSpot, but not guaranteed either way):

Output
volatile reader stopped
volatile reader alive after 2 s: false
plain reader alive after 2 s:    true
  • The plain reader never stopped and never printed its message. Once the JIT compiled its loop, it saw that nothing in the loop writes plainStop, read the field once, and turned the loop into an endless one. This is a legal optimization: without a happens-before edge, the JMM does not require a thread to ever see another thread's write.
  • The volatile reader stopped at once. A volatile read must observe the latest write to that field, so it cannot be hoisted out of the loop.
  • The program only ended because the stuck thread was a daemon. In a server, the same bug is a worker that ignores its shutdown flag forever. Before the JIT compiles the loop, the plain reader often does see the change, which is why this bug can pass every test and appear only under load.

Reordering: two reads that both see zero

Thread A writes x = 1 then reads y; thread B writes y = 1 then reads x. If each thread's two steps ran in order, at least one of them would read 1, because whichever read comes last follows both writes. The program runs this race 1,000,000 times with plain fields and again with volatile fields, and counts the rounds in which both threads read 0.

Java
import java.util.concurrent.CyclicBarrier;

public class Reordering {

    static int x, y, r1, r2;                       // plain fields
    static volatile int vx, vy;                    // the same test with volatile fields
    static int vr1, vr2;

    public static void main(String[] args) throws Exception {
        int rounds = 1000000;
        int plain = race(rounds, () -> { x = 1; r1 = y; }, () -> { y = 1; r2 = x; },
                () -> r1 == 0 && r2 == 0, () -> { x = 0; y = 0; });
        int vol = race(rounds, () -> { vx = 1; vr1 = vy; }, () -> { vy = 1; vr2 = vx; },
                () -> vr1 == 0 && vr2 == 0, () -> { vx = 0; vy = 0; });
        System.out.println("rounds per test:                 " + rounds);
        System.out.println("plain fields,    both read 0:    " + plain + " times");
        System.out.println("volatile fields, both read 0:    " + vol + " times");
    }

    interface Check {
        boolean test();
    }

    // Runs the two bodies at the same moment, many times, and counts rounds where check is true
    static int race(int rounds, Runnable bodyA, Runnable bodyB, Check check, Runnable reset)
            throws Exception {
        CyclicBarrier start = new CyclicBarrier(2);
        CyclicBarrier end = new CyclicBarrier(3);
        Thread a = new Thread(() -> repeat(rounds, start, end, bodyA));
        Thread b = new Thread(() -> repeat(rounds, start, end, bodyB));
        a.start();
        b.start();
        int hits = 0;
        for (int i = 0; i < rounds; i++) {
            end.await();                           // both threads finished this round
            if (check.test()) {
                hits++;
            }
            reset.run();
            end.await();                           // reset done, next round may start
        }
        a.join();
        b.join();
        return hits;
    }

    static void repeat(int rounds, CyclicBarrier start, CyclicBarrier end, Runnable body) {
        try {
            for (int i = 0; i < rounds; i++) {
                start.await();
                body.run();
                end.await();
                end.await();
            }
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }
}

Output (the plain count changes every run and can be 0; the volatile count is always 0):

Output
rounds per test:                 1000000
plain fields,    both read 0:    8 times
volatile fields, both read 0:    0 times
  • With plain fields, both threads read 0 in a few rounds out of a million (the count varies; repeated runs here gave between 0 and a few dozen), a result that is impossible if each thread runs in program order. Each core put its write into its store buffer and then performed the read before the write had become visible to the other core. x86 allows exactly this one kind of reordering, a store followed by a load; ARM processors, as in many cloud servers and Apple machines, allow more kinds.
  • With volatile fields the count is 0, and the JMM guarantees it. All volatile reads and writes appear to every thread in one total order consistent with each thread's program order. On x86 the JIT enforces this by following each volatile write with a full fence (a lock-prefixed instruction), which waits for the store buffer to drain.

Atomicity: volatile does not make ++ safe

Two threads each increment three counters 100,000 times: a volatile int, an int guarded by a lock, and an AtomicInteger. The right total for each is 200,000.

Java
import java.util.concurrent.atomic.AtomicInteger;

public class Atomicity {

    static volatile int volatileCount;
    static int lockedCount;
    static final AtomicInteger atomicCount = new AtomicInteger();
    static final Object LOCK = new Object();

    public static void main(String[] args) throws InterruptedException {
        Runnable work = () -> {
            for (int i = 0; i < 100000; i++) {
                volatileCount++;                 // read, add, write: three steps
                synchronized (LOCK) {
                    lockedCount++;               // one thread at a time
                }
                atomicCount.incrementAndGet();   // one atomic hardware operation
            }
        };
        Thread t1 = new Thread(work);
        Thread t2 = new Thread(work);
        t1.start();
        t2.start();
        t1.join();
        t2.join();

        System.out.println("expected:          200000");
        System.out.println("volatile int++:    " + volatileCount);
        System.out.println("synchronized ++:   " + lockedCount);
        System.out.println("AtomicInteger:     " + atomicCount.get());
    }
}

Output (the volatile count differs every run; the other two are always 200000):

Output
expected:          200000
volatile int++:    199646
synchronized ++:   200000
AtomicInteger:     200000

volatileCount++ is three steps: read, add 1, write. Both threads can read the same value, both add 1, and both write the same result, so one increment disappears. How many are lost varies from run to run, from a handful to several thousand. volatile made every write visible, but visibility was never the problem: the two steps need to happen as one. A lock makes the whole read-modify-write exclusive, and incrementAndGet uses a single atomic CPU instruction (lock xadd on x86). For more on the atomic classes, see atomic classes.

A related, rarer case is word tearing: JLS 17.7 allows a non-volatile long or double write to be split into two 32-bit halves. A reader could then see half of an old value and half of a new one. 64-bit HotSpot JVMs write them in one piece, but declaring the field volatile makes it guaranteed.

The happens-before rules

The JMM does not talk about caches or fences. It defines one relation: if action A happens-before action B, then B sees the effects of A and of everything that happened before A in A's thread. The rules that create these edges are:

  • Program order: within one thread, each action happens-before every later action in that thread.
  • Monitor lock: releasing a lock happens-before every later acquisition of the same lock.
  • Volatile: a write to a volatile field happens-before every later read of that same field.
  • Thread start: t.start() happens-before every action of t.
  • Thread end: every action of t happens-before another thread returns from t.join() or sees t.isAlive() return false.
  • Interruption: t.interrupt() happens-before t detects the interrupt.
  • Transitivity: if A happens-before B and B happens-before C, then A happens-before C.

Transitivity is what makes a single volatile flag enough to publish many plain fields. The writer sets three plain fields and then the volatile ready; the reader waits for ready and then reads the plain fields. The program repeats this 20,000 times with fresh values and checks every field each time.

Java
public class HappensBefore {

    // Plain fields, published by one volatile write
    static int width, height;
    static String label;
    static volatile boolean ready;

    public static void main(String[] args) throws InterruptedException {
        int rounds = 20000;
        int inconsistent = 0;
        for (int i = 1; i <= rounds; i++) {
            int expected = i;
            ready = false;
            width = 0;
            height = 0;
            label = null;
            int[] seen = new int[1];
            Thread reader = new Thread(() -> {
                while (!ready) {                   // volatile read
                    Thread.onSpinWait();
                }
                // Everything written before 'ready = true' is now visible
                if (width != expected || height != expected * 2 || label == null) {
                    seen[0] = 1;
                }
            });
            reader.start();
            width = expected;                      // plain writes ...
            height = expected * 2;
            label = "box " + expected;
            ready = true;                          // ... made visible by this volatile write
            reader.join();
            inconsistent += seen[0];
        }
        System.out.println("rounds:                       " + rounds);
        System.out.println("reader saw half-written data: " + inconsistent + " times");
    }
}

Output:

Output
rounds:                       20000
reader saw half-written data: 0 times

The count is 0 and is guaranteed to be 0. The plain writes come before ready = true in program order; that volatile write happens-before the reader's volatile read that sees true; and that read comes before the plain reads in the reader's program order. Chained together, every plain write happens-before every plain read. The guarantee is one-directional: writes made after ready = true are not covered, and the reader must read the volatile first.

The java.util.concurrent classes document their edges in the same terms. Putting an object into a BlockingQueue or ConcurrentHashMap happens-before taking it out, submitting a task to an executor happens-before it runs, a task's actions happen-before Future.get returns, and countDown() happens-before the matching await() returns. That is why handing data over through these classes needs no volatile at all.

Safe publication and double-checked locking

Publishing an object means making a reference to it reachable by another thread. The reader must see not only the reference but also every field the constructor set. Lazy initialization of a shared service is where this goes wrong most often. The program has four threads ask for the service at the same moment, using three strategies, and counts how many times the constructor ran. The constructor sleeps 50 ms so that the race window is wide and the result is stable.

Java
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;

public class SafePublication {

    static final Set<Integer> CREATED = ConcurrentHashMap.newKeySet();

    static final class Service {
        final int id;

        Service(int id) {
            sleep(50);                                 // a slow constructor widens the race
            this.id = id;
            CREATED.add(id);
        }
    }

    // 1. Broken: check-then-act on a plain field
    static Service racy;

    static Service getRacy(int caller) {
        if (racy == null) {
            racy = new Service(caller);
        }
        return racy;
    }

    // 2. Double-checked locking: correct only because the field is volatile
    static volatile Service dcl;

    static Service getDcl(int caller) {
        Service s = dcl;                               // one volatile read on the fast path
        if (s == null) {
            synchronized (SafePublication.class) {
                s = dcl;
                if (s == null) {
                    s = new Service(caller);
                    dcl = s;
                }
            }
        }
        return s;
    }

    // 3. Holder idiom: the JVM initializes Holder once, on first use, under its own lock
    static final class Holder {
        static final Service INSTANCE = new Service(99);
    }

    interface Getter {
        Service get(int caller);
    }

    public static void main(String[] args) throws InterruptedException {
        run("plain lazy init", SafePublication::getRacy);
        run("volatile DCL", SafePublication::getDcl);
        run("holder class", caller -> Holder.INSTANCE);
    }

    static void run(String name, Getter getter) throws InterruptedException {
        CREATED.clear();
        CountDownLatch go = new CountDownLatch(1);
        Set<Service> returned = ConcurrentHashMap.newKeySet();
        Thread[] threads = new Thread[4];
        for (int i = 0; i < threads.length; i++) {
            int caller = i;
            threads[i] = new Thread(() -> {
                await(go);
                returned.add(getter.get(caller));
            });
            threads[i].start();
        }
        go.countDown();                                // release all four at once
        for (Thread t : threads) {
            t.join();
        }
        System.out.printf("%-16s constructors run: %d, distinct instances returned: %d%n",
                name, CREATED.size(), returned.size());
    }

    static void await(CountDownLatch latch) {
        try {
            latch.await();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    static void sleep(long ms) {
        try {
            Thread.sleep(ms);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}

Output:

Output
plain lazy init  constructors run: 4, distinct instances returned: 4
volatile DCL     constructors run: 1, distinct instances returned: 1
holder class     constructors run: 1, distinct instances returned: 1
  • Plain lazy initialization built the "singleton" 4 times and handed out 4 different objects. All four threads saw null before any of them finished the constructor. With a fast constructor the window is smaller, but the bug is the same.
  • Double-checked locking ran the constructor once. It works only because dcl is volatile. Without it, the JIT may write the reference to the field before the constructor's field writes are visible, and a thread on the unlocked fast path could see a non-null object whose fields are still zero. This was the famous broken idiom before Java 5. Reading the field into a local s means the fast path costs one volatile read.
  • The holder idiom ran the constructor once with no explicit synchronization. The JVM runs a class's static initializer exactly once, under an internal lock, the first time the class is used (JLS 12.4.2), and initialization happens-before any use. It is the simplest correct lazy singleton.

The other safe ways to publish an object are: a static final field set at class initialization; a thread-safe collection or queue; storing and reading under the same lock; and making all of the object's fields final. For final fields, JLS 17.5 guarantees that any thread that obtains a reference to the object after its constructor finished sees the values the constructor assigned, even if the reference itself was shared through a data race. The condition is that the constructor does not let this escape, for example by registering a listener or starting a thread that uses this. This is why immutable objects are thread-safe; see immutability.

What the fixes cost

Each strategy adds 1 to a counter 20 million times on one thread. Each test runs 3 times and the fastest is reported. This is a rough comparison, not a benchmark; the JMH page shows how to measure properly.

Java
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;
import java.util.function.IntConsumer;

public class SyncCost {

    static long plain;
    static volatile long vol;
    static long locked;
    static final Object LOCK = new Object();
    static final AtomicLong ATOMIC = new AtomicLong();
    static final LongAdder ADDER = new LongAdder();

    // Each loop is its own method, so the JIT compiles each one separately
    static void plainLoop(int n) {
        for (int i = 0; i < n; i++) {
            plain++;
        }
    }

    static void volatileLoop(int n) {
        for (int i = 0; i < n; i++) {
            vol++;                                 // not atomic: only used by one thread
        }
    }

    static void lockLoop(int n) {
        for (int i = 0; i < n; i++) {
            synchronized (LOCK) {
                locked++;
            }
        }
    }

    static void atomicLoop(int n) {
        for (int i = 0; i < n; i++) {
            ATOMIC.incrementAndGet();
        }
    }

    static void adderLoop(int n) {
        for (int i = 0; i < n; i++) {
            ADDER.increment();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        int n = 20000000;
        System.out.printf("%,d increments on one thread, best of 3 runs%n", n);
                time("plain long", 1, n, SyncCost::plainLoop);
        time("volatile long", 1, n, SyncCost::volatileLoop);
        time("synchronized", 1, n, SyncCost::lockLoop);
        time("AtomicLong", 1, n, SyncCost::atomicLoop);
        time("LongAdder", 1, n, SyncCost::adderLoop);
        System.out.println("final values: " + locked + ", " + ATOMIC.get() + ", " + ADDER.sum());
    }

    static void time(String name, int threads, int n, IntConsumer loop)
            throws InterruptedException {
        long best = Long.MAX_VALUE;
        for (int run = 0; run < 3; run++) {
            Thread[] ts = new Thread[threads];
            for (int i = 0; i < threads; i++) {
                ts[i] = new Thread(() -> loop.accept(n / threads));
            }
            long t0 = System.nanoTime();
            for (Thread t : ts) {
                t.start();
            }
            for (Thread t : ts) {
                t.join();
            }
            best = Math.min(best, System.nanoTime() - t0);
        }
        System.out.printf("  %-14s %5.1f ns per increment%n", name, (double) best / n);
    }
}

Output (2-CPU Linux machine, JDK 21; absolute numbers will differ on yours):

Output
20,000,000 increments on one thread, best of 3 runs
  plain long       0.0 ns per increment
  volatile long    6.4 ns per increment
  synchronized     4.4 ns per increment
  AtomicLong       4.8 ns per increment
  LongAdder        8.4 ns per increment
final values: 60000000, 60000000, 60000000
  • The plain loop shows 0.0 ns because the JIT replaced 20 million increments by a single addition of 20 million. That is the same freedom that made the plain reader loop forever: with no synchronization, the compiler may assume no other thread is looking.
  • The volatile, synchronized and atomic loops all cost a few nanoseconds per increment, because each one must really perform the memory operation with a fence or an atomic instruction. Uncontended locks are cheap in modern HotSpot, and the JIT may also merge lock regions of neighbouring iterations (lock coarsening), so a synchronized loop like this one can look cheaper than locking does in real code.
  • LongAdder is slower than AtomicLong on one thread. It is built for contention: when threads collide on its base value, it spreads updates over separate cells and adds them up in sum(). Its Javadoc promises significantly higher throughput under high contention, at the cost of more memory, so use it for counters that many threads update and few read.
  • The last line prints the synchronized, atomic and adder counters: each reached 60,000,000, three runs of 20 million. On one thread that is expected; the point of these classes is that the totals stay exact when many threads share them, as the atomicity section showed.

Choosing the right tool

Which mechanism fits which sharing pattern
SituationUse
A stop flag or status read by other threadsvolatile boolean
Publishing a fully built object to other threadsA volatile reference, or a final field of an immutable object
A counter or a single value updated by many threadsAtomicInteger, AtomicLong, or LongAdder for heavy contention
Several fields that must change togethersynchronized or a Lock
A lazily created singletonThe holder class idiom, or an enum
Handing data from one thread to anotherA BlockingQueue or ConcurrentHashMap
Data used by one thread onlyNothing: confinement needs no synchronization

See synchronized and volatile for the keywords in detail, VarHandle for the weaker access modes, and thread basics for start, join and interruption.