Introduction
The Java Memory Model JMM was standardised by JSR-133 and shipped in Java 5 (September 2004), then formalised by Jeremy Manson and William Pugh in their POPL 2005 paper "The Java Memory Model" which the Java Language Specification still cites in Chapter 17 today. Before Java 5, the JMM was loosely specified in roughly two pages of prose, and the gaps let JIT compilers reorder reads and writes so aggressively that double-checked locking broke silently and final fields could be seen half-constructed by other threads. JSR-133 closed those gaps by introducing the happens-before relationship, which is now the backbone of every concurrency primitive in the JDK.
For a Java learner, the Java Memory Model JMM is the difference between "my code works on my laptop" and "my code works under every CPU, every JIT optimisation, every thread interleaving". Multi-core CPUs and the HotSpot JIT both reorder instructions aggressively, and CPU caches defer writes for tens of nanoseconds. The JMM is the contract that tells you when one thread is guaranteed to see another thread's writes. Without that contract the classic race on a boolean ready flag can loop forever, a volatile long could be torn across two 32-bit writes on a 32-bit JVM, and a lazily-initialised singleton can be published before its constructor finishes. This post explains visibility, atomicity, ordering, and the three keywords that bring them under control: volatile, final, and synchronized.
What is the Java Memory Model JMM?
The Java Memory Model JMM is the formal specification of how the JVM threads interact through main memory. It defines three guarantees that the JVM makes between threads: visibility (when a write by one thread becomes visible to another thread), atomicity (which read and write operations are indivisible), and ordering (when operations that appear in source code in one order may legitimately be observed in a different order by another thread). Every concurrency keyword in the JDK -- volatile, synchronized, final, java.util.concurrent.locks.Lock, AtomicInteger -- is a thin wrapper around the JMM rules.
The category breakdown is: data-race freedom (the JMM calls this "correctly synchronised"), happens-before edges (the formal ordering relation that the JMM uses to define safe publication), and the three keywords. volatile guarantees visibility of a single field and prevents reordering of accesses to that field across the volatile read/write. final guarantees safe publication of fields set in the constructor, even without synchronisation. synchronized provides both mutual exclusion (mutex on the monitor) and a memory barrier (release on exit, acquire on enter). The distinction matters: a volatile counter increment is not atomic because read-modify-write is three steps, but a volatile flag publication is safe because it is a single write.
How the Java Memory Model JMM Works - Step by Step
Step 1: Threads and working memory. The JMM abstracts the CPU cache hierarchy by saying each thread has its own working memory that holds a copy of the variables it touches. Writes go to working memory first, then are flushed to main memory at certain events -- a volatile write, a synchronized block exit, a thread start, a Thread.join return. Reads come from working memory, refreshed from main memory at certain events -- a volatile read, a synchronized block entry, a Thread.start. Without those events the JIT may keep a field in a register indefinitely, which is why the classic while (!stop) loop never terminates without volatile on stop.
Step 2: Volatile variable rule. A volatile write happens-before every subsequent volatile read of the same field. This is one of the eight JMM rules, and it means a thread that writes volatile ready = true after setting number = 42 publishes both: any thread that reads ready == true is also guaranteed to see number == 42. Volatile also prevents the compiler from hoisting a read out of a loop, which is what stops the infinite loop in the while (!stop) example. Volatile gives visibility but not atomicity: x++ on a volatile int is still three steps and is racy.
Step 3: Final field rule. The JMM gives final fields a special guarantee: once a constructor of an object completes, any thread that obtains a reference to that object is guaranteed to see the final fields with their constructor-set values, even without synchronisation. This is called safe publication. The trick is that the JIT inserts a memory barrier at the end of any constructor that writes final fields, so the writes are flushed before the object reference escapes. Non-final fields do not get this guarantee, which is why an object with mutable fields can be seen with default values (0, false, null) by a concurrent reader.
Step 4: Monitor lock rule. A synchronized block has two effects. First, mutual exclusion: only one thread at a time can hold the monitor. Second, memory barrier: every write inside the block is flushed to main memory on exit, and every read inside the block is refreshed from main memory on entry. This means a thread that releases a lock publishes all its writes to any thread that later acquires the same lock. AtomicInteger and the other java.util.concurrent.atomic classes use the same happens-before edge internally, which is why AtomicInteger.compareAndSet is a memory barrier.
Step 5: Atomicity and the long/double exception. The JMM guarantees that reads and writes of all primitive types except long and double are atomic. A non-volatile long or double write is permitted to be split into two 32-bit writes by the JVM, which on a 32-bit CPU could expose a torn value (the high 32 bits of one write mixed with the low 32 bits of another). Declaring the field volatile forces the JVM to use a single 64-bit write, so volatile longs and doubles are both visible and atomic. This is the only case where volatile adds atomicity.
Java Program for the Java Memory Model JMM
import java.util.concurrent.atomic.AtomicInteger;
public class JmmDemo {
// Volatile field: writes visible to all threads, plus HB edge
private static volatile int volatileCounter = 0;
// Non-volatile field: writes may be cached and reordered
private static int nonVolatileCounter = 0;
// Final field for safe publication
private final int finalValue;
public JmmDemo(int v) {
this.finalValue = v;
// final guarantees visibility to other threads without sync
}
public int getFinal() {
return finalValue;
}
public static void main(String[] args) throws InterruptedException {
// --- Volatile Variable Rule ---
Thread writer = new Thread(() -> {
try { Thread.sleep(50); } catch (InterruptedException e) { }
nonVolatileCounter = 1;
volatileCounter = 1; // volatile write publishes nonVolatileCounter
System.out.println("Writer published values");
});
Thread reader = new Thread(() -> {
int spins = 0;
// Once we see volatileCounter == 1, the non-volatile write is also visible
while (volatileCounter != 1) {
spins++;
}
System.out.println("Reader saw volatile after " + spins + " spins");
System.out.println("nonVolatileCounter = " + nonVolatileCounter);
});
reader.start();
writer.start();
reader.join();
writer.join();
// --- Final Field Rule (safe publication) ---
JmmDemo d = new JmmDemo(42);
System.out.println("Final field seen: " + d.getFinal());
// --- AtomicInteger HB edge ---
AtomicInteger ai = new AtomicInteger(0);
Thread t1 = new Thread(() -> ai.set(5));
Thread t2 = new Thread(() -> ai.compareAndSet(5, 10));
t1.start(); t1.join();
t2.start(); t2.join();
System.out.println("AtomicInteger final value: " + ai.get());
}
}
Code Explanation - Line by Line
The class declares two static counters, one volatile and one not, to demonstrate the difference a single keyword makes. The volatileCounter field is marked volatile; every write to it is flushed to main memory immediately and every read is refreshed from main memory, plus the volatile write creates a happens-before edge that also publishes nonVolatileCounter. The nonVolatileCounter field is a normal int with no special memory guarantees; without the volatile edge on its sibling field, the reader thread could in principle see the default value 0 forever.
The finalValue field demonstrates the final field rule. The JMM inserts a memory barrier at the end of every constructor that writes a final field, so when the constructor returns the value 42 is guaranteed visible to any thread that subsequently reads it via getFinal(), even if no synchronisation is used. Without final, the JIT would be permitted to reorder the field write past the end of the constructor, and a thread that obtained the reference through a data race could see finalValue == 0.
The writer thread sleeps for 50 milliseconds to let the reader thread start spinning first, then writes the non-volatile counter and then the volatile counter. The ordering of the two writes is preserved because the volatile write acts as a release barrier: everything that happened before it in program order is flushed to main memory before the volatile value is. The reader thread spins on the volatile field until it observes the value 1, then prints both fields. In practice the reader will always observe nonVolatileCounter == 1 because the JMM's volatile rule says so; on a JVM without the JMM (or with a buggy compiler) this would not be guaranteed.
The AtomicInteger section shows that AtomicInteger provides the same happens-before edge as a synchronized block, but without the lock. ai.set(5) is a release, ai.compareAndSet(5, 10) is an acquire-and-release, and the join on each thread guarantees that the writer's actions are visible to the main thread. This is why the JDK docs say that the atomic classes have memory consistency effects equivalent to volatile.
Interview Questions and Answers
Q1. What is the Java Memory Model and why does it exist?
The Java Memory Model (JMM) is the formal specification, defined in JSR-133 and shipped in Java 5, that describes how threads interact through main memory. It exists because CPU caches and the JIT both reorder instructions, so without a contract a thread could observe stale or partially-constructed values from another thread. The JMM gives the programmer a set of rules (volatile, final, synchronized, happens-before) that pin down when one thread is guaranteed to see another thread's writes.
Q2. What does the volatile keyword do?
Declaring a field volatile guarantees visibility and ordering for that field: every write is flushed to main memory immediately, every read is refreshed from main memory, and the compiler cannot hoist reads out of loops or reorder accesses across the volatile access. A volatile write also happens-before every subsequent volatile read of the same field, which means it can be used to publish non-volatile fields. Volatile does not provide atomicity for compound operations like x++, which is still three steps (read, add, write) and remains racy.
Q3. What is the happens-before relationship?
Happens-before is the formal ordering relation the JMM uses to define memory visibility. If action A happens-before action B, then the effects of A are visible to B. The JMM defines happens-before through eight rules: program order, volatile variable, monitor lock, thread start, thread termination, thread interruption, object finalizer, and the transitivity rule. A correct program is one where conflicting accesses are ordered by happens-before; otherwise you have a data race and the JMM gives no guarantees about what the program observes.
Q4. How do final fields provide safe publication?
The JMM inserts a memory barrier at the end of any constructor that writes a final field, so the field values are flushed to main memory before the object reference can escape. This means any thread that obtains a reference to the object -- even through a data race -- is guaranteed to see the final fields with their constructor-set values. Without final, a reader could see a non-final field with its default value (0, false, null) because the JIT is free to reorder the field write past the constructor return.
Q5. What is the difference between volatile and synchronized?
Both provide memory visibility (the volatile write is a release, the synchronized exit is a release), but synchronized also provides mutual exclusion -- only one thread can hold the monitor at a time. Use volatile for a single writable flag or single 64-bit value that is published by one thread and read by others, and use synchronized when you need atomicity for a compound operation like read-modify-write. Synchronized is heavier (lock acquisition, monitor inflation, context switch under contention), while volatile is essentially free on modern CPUs.
Q6. Is writing to a long atomic in Java?
Writes to a non-volatile long or double are not guaranteed to be atomic; the JVM is permitted to split them into two 32-bit writes, which on a 32-bit CPU could expose a torn value to a concurrent reader. Declaring the field volatile forces the JVM to use a single 64-bit write, which is both visible and atomic. Reads and writes of all other primitive types (int, boolean, byte, char, short, float, references) are guaranteed atomic by the JMM even without volatile, though visibility is still not guaranteed without a happens-before edge.
Q7. Why does the classic double-checked locking pattern need volatile on the holder field?
In double-checked locking you check a flag, and only if it is null do you acquire the lock and create the singleton. Without volatile on the holder, the JMM permits the constructor's field writes to be reordered with the assignment to the holder reference, so a thread that sees the holder as non-null may see it with its fields still at their default values. Marking the holder volatile forces the write to be a release, so all constructor writes are flushed before the reference is published. In modern Java, the preferred pattern is to use a static final holder field (the "initialisation-on-demand holder" idiom) which uses the JMM's class initialisation guarantees instead.
Sample Input and Output
Input: Run JmmDemo with two worker threads on a multi-core JVM. Output: Writer published values Reader saw volatile after 4231 spins nonVolatileCounter = 1 Final field seen: 42 AtomicInteger final value: 10
The output shows that the reader thread observed the volatile counter after roughly 4231 spins (the exact count depends on CPU scheduling, OS, and JVM version) and immediately saw the non-volatile counter as 1, demonstrating that the volatile write published the non-volatile write. The final field value of 42 was visible without any synchronisation, demonstrating safe publication, and the AtomicInteger ended at 10, demonstrating that compareAndSet applied the happens-before edge.
Common Mistakes to Avoid
First, do not assume that volatile int counter; counter++ is atomic. The ++ is read, add, write -- three steps -- and two threads doing it concurrently can lose increments. Use AtomicInteger or synchronized for counters. Second, do not publish a non-final mutable field through a data race. A private Map cache; without volatile or final can be seen as null by another thread, leading to a NullPointerException that is impossible to reproduce on a single-threaded test.
Third, do not confuse visibility with atomicity. A volatile boolean ready is fine for a stop flag (single write, many reads) but a volatile int nextId is wrong for an id generator (compound read-modify-write). Fourth, do not rely on program order to provide visibility across threads; program order is intra-thread, and the JMM only crosses threads through the eight happens-before rules. Finally, do not assume that calling a thread's start() method is enough to see writes that happen after start() in the calling thread -- only writes that happened before start() are guaranteed visible to the started thread.
Real-World Applications
The Java Memory Model JMM underpins every concurrent construct in the JDK. java.util.concurrent.ConcurrentHashMap relies on volatile reads of the bucket array to provide lock-free reads. java.util.concurrent.atomic.AtomicInteger and friends piggyback on the volatile happens-before edge. Spring's singleton bean factory publishes beans via static final holders, which uses the final field rule. The ThreadLocal pattern uses the thread start rule to pass the initial value to the thread. Java Persistence API implementations use volatile fields on lazily-loaded entity proxies to publish the loaded state.
Beyond the JDK, the JMM is the model that Java Concurrency in Practice (Brian Goetz et al., 2006) is built on, and the same happens-before formalism underpins the C++11 memory model and the Go memory model. Android's Handler and Looper use the JMM to publish messages across threads. Reactive Streams backpressure uses a volatile long field for the demand counter. Anywhere you see a thread passing data to another thread, you are using the JMM -- and the JDK is full of such places.
Conclusion
The Java Memory Model JMM is the contract that makes concurrent Java programs predictable: it defines visibility, atomicity, and ordering through the happens-before rules and the volatile, final, and synchronized keywords. Mastering these rules lets you write lock-free code that is still correct. Next, study the happens-before relationship in depth, the java.util.concurrent package (locks, atomics, collections), and the patterns in Java Concurrency in Practice.
Comments
Comments
Post a Comment