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.
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
- 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:
| Tool | Since | Visibility | Ordering | Atomic read-modify-write | Best for |
|---|---|---|---|---|---|
volatile | Java 1.0 (strengthened in Java 5) | Yes | Yes | No | Flags and published references |
synchronized | Java 1.0 | Yes | Yes | Yes, inside the block | Updating several fields together |
final | Java 5 semantics | After construction | Yes | Not applicable | Immutable objects |
| Atomic classes | Java 5 | Yes | Yes | Yes, one variable | Counters, single-value state |
VarHandle | Java 9 | Depends on mode | Depends on mode | Yes (CAS, getAndAdd) | Library code needing weaker, cheaper modes |
java.util.concurrent | Java 5 | Yes, documented per class | Yes | Per class | Most 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 volatilemain
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):
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
, 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.plainStop - The volatile reader stopped at once. A
read must observe the latest write to that field, so it cannot be hoisted out of the loop.volatile - 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 = 1yy = 1x
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):
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
-prefixed instruction), which waits for the store buffer to drain.lock
Atomicity: volatile does not make ++ safe
Two threads each increment three counters 100,000 times: a volatile intintAtomicInteger
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):
expected: 200000
volatile int++: 199646
synchronized ++: 200000
AtomicInteger: 200000
volatileCount++volatileincrementAndGetlock xadd
A related, rarer case is word tearing: JLS 17.7 allows a non-volatile longdoublevolatile
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:
happens-before every action oft.start() .t - Thread end: every action of
happens-before another thread returns fromt or seest.join() return false.t.isAlive() - Interruption:
happens-beforet.interrupt() detects the interrupt.t - 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 readyready
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:
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 = trueready = true
The java.util.concurrentBlockingQueueConcurrentHashMapFuture.getcountDown()await()volatile
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.
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:
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
before any of them finished the constructor. With a fast constructor the window is smaller, but the bug is the same.null - Double-checked locking ran the constructor once. It works only because
isdcl . 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 localvolatile means the fast path costs one volatile read.s - 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 finalfinalthisthis
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
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):
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.
is slower thanLongAdder 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 inAtomicLong . 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.sum()- 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
| Situation | Use |
|---|---|
| A stop flag or status read by other threads | volatile boolean |
| Publishing a fully built object to other threads | A volatilefinal |
| A counter or a single value updated by many threads | AtomicIntegerAtomicLongLongAdder |
| Several fields that must change together | synchronized |
| A lazily created singleton | The holder class idiom, or an enum |
| Handing data from one thread to another | A |
| Data used by one thread only | Nothing: confinement needs no synchronization |
See startjoin