The Java Memory Model

Why threads can see stale or reordered values, the happens-before relation, volatile, synchronized, final-field semantics, safe publication, double-checked locking, and data races.

Advanced 6 min readLesson 13 of 14 Interview Q&A

The Java Memory Model (JMM), defined in JLS chapter 17, answers a question that sounds trivial: when one thread writes a variable, when will another thread see the new value? The answer is: only when the program guarantees it — otherwise, possibly never, or in a surprising order.

Why intuition fails

Two things break the naive "all threads see one shared memory in program order" model:

  1. Caches and store buffers: each core has private caches and a store buffer; a write may sit there before becoming visible to other cores (Cache memory).
  2. Reordering: the compiler (javac, the JIT) and the CPU reorder instructions when it doesn't change single-threaded behaviour. Loads can be hoisted out of loops; independent writes can be swapped.

Visibility failure

Java
class Worker {
    private boolean running = true;          // NOT volatile

    void run() {
        while (running) { /* work */ }       // JIT may hoist the read: while (true)
    }
    void stop() { running = false; }         // called from another thread
}

The worker may never stop: the JIT sees no write to running inside the loop and is allowed to read it once.

Reordering failure

Java
int x = 0, y = 0, a = 0, b = 0;
// Thread 1          // Thread 2
a = 1;               b = 1;
x = b;               y = a;

Intuitively at least one of x, y must be 1. Yet x == 0 && y == 0 is a legal — and observable — outcome, because each thread's two independent statements can be reordered (or the writes delayed in store buffers).

Happens-before

The JMM defines a partial order called happens-before (HB). If action A happens-before action B, then A's effects are visible to B and A appears ordered before B. Without an HB relationship between a write and a read in different threads, you have a data race and no guarantees.

HB edges come from:

RuleEdge
Program orderEach action in a thread HB every later action in that thread
Monitor lockUnlocking a monitor HB every subsequent lock of the same monitor
volatileA write to a volatile field HB every subsequent read of that field
Thread startt.start() HB every action in thread t
Thread joinEvery action in t HB another thread's successful return from t.join()
Interruptiont.interrupt() HB t detecting the interrupt
Finalizer / constructorEnd of a constructor HB the start of its finalizer
TransitivityIf A HB B and B HB C, then A HB C
java.util.concurrentE.g. putting into a BlockingQueue HB taking it out; actions before submit() HB the task; Future.get() sees the task's effects
Thread AmemoryThread Bdata = 42 (plain write)ready = true (volatile write)reads ready == true (volatile read)reads data → guaranteed 42

Transitivity is the key: data = 42 HB the volatile write (program order), which HB the volatile read, which HB reading data. So the plain write to data is published by the volatile write.

volatile

A volatile field guarantees:

  • Visibility: reads always see the latest write (no caching in registers, no hoisting).
  • Ordering: writes before a volatile write can't move after it; reads after a volatile read can't move before it (acquire/release semantics).
  • Atomicity of the single read or write — even for long and double, which otherwise may tear on 32-bit JVMs.

It does not make compound actions atomic:

Java
volatile int count;
count++;            // still a race: read, add, write

Use volatile for flags, publishing immutable objects and state read by many, written by one. Use locks or atomics for read-modify-write.

Java
class Worker {
    private volatile boolean running = true;     // fixes the infinite loop
    void run() { while (running) { ... } }
    void stop() { running = false; }
}

synchronized and visibility

Locks are about more than mutual exclusion: unlocking flushes your writes (release) and locking sees everything published before the last unlock of the same lock (acquire). That's why reads of shared mutable state also need the lock — a synchronized setter with an unsynchronised getter is broken.

final fields

The JMM gives final fields a special guarantee: once a constructor finishes, any thread that obtains a reference to the object (even through a race) sees the correctly initialised values of its final fields (and of objects reachable through them, as of the end of the constructor). Non-final fields have no such guarantee.

This is why immutable objects (all fields final, no this escape during construction) are thread-safe without synchronisation.

Safe publication

Making an object visible to other threads correctly requires publishing its reference through an HB edge. Safe ways:

  • Store it in a volatile field or an AtomicReference.
  • Store it in a field guarded by a lock (both writer and readers lock).
  • Store it in a final field of a properly constructed object.
  • Initialise it in a static initialiser (class init is synchronised by the JVM).
  • Put it in a thread-safe collection (ConcurrentHashMap, BlockingQueue).

Unsafe publication (a plain field written by one thread, read by another) can expose a partially constructed object: the reference becomes visible before the constructor's writes.

Double-checked locking, revisited

Java
private static Helper instance;            // BROKEN without volatile
static Helper get() {
    if (instance == null) {                // unsynchronised read (racy)
        synchronized (Helper.class) {
            if (instance == null) instance = new Helper();
        }
    }
    return instance;
}

instance = new Helper() is: allocate, construct, assign. Assignment may become visible before construction completes. A second thread sees non-null at the first check, skips the lock, and uses a half-built object. Declaring instance volatile adds the needed HB edge. The holder idiom avoids the issue entirely (Singleton).

Data races vs race conditions

  • A data race (JMM term): two threads access the same variable, at least one writes, and the accesses aren't ordered by happens-before. Results are undefined by the model.
  • A race condition: a correctness bug depending on timing — possible even without data races (e.g. check-then-act with individually synchronised calls).

Correctly synchronised programs (free of data races) are guaranteed sequential consistency: they behave as if all actions occurred in one global order consistent with each thread's program order. That's the deal the JMM offers: synchronise properly, and you can reason intuitively.

Beyond volatile: VarHandles

java.lang.invoke.VarHandle (Java 9) exposes finer-grained access modes for library authors — plain, opaque, acquire/release, and volatile — plus CAS on fields and array elements. It's how java.util.concurrent is implemented today. Application code should stick to higher-level tools.

Key takeaways
  • Without synchronisation, threads may see stale values or reordered writes.
  • Happens-before defines visibility: program order, locks, volatile, start/join, and j.u.c. hand-offs, combined transitively.
  • volatile gives visibility and ordering, not atomicity of compound actions.
  • final fields of properly constructed objects are visible without synchronisation — immutability is thread-safe.
  • Publish shared objects safely; double-checked locking needs volatile.
  • Data-race-free programs are sequentially consistent.
Interview questions
QWhat does volatile guarantee in Java?medium

Visibility (a read sees the most recent write to that variable by any thread), ordering (a volatile write acts as a release barrier and a volatile read as an acquire barrier, so writes before the volatile write are visible to threads that read it), and atomic reads/writes even for long and double. It does not make compound operations like count++ atomic.

QWhat is happens-before?hard

A partial ordering of actions defined by the Java Memory Model: if A happens-before B, A's effects are visible to B. Edges come from program order within a thread, unlocking then locking the same monitor, writing then reading the same volatile variable, Thread.start and join, and concurrency utilities, and the relation is transitive. Two conflicting accesses not ordered by happens-before constitute a data race.