- Prerequisites
- 1.2 Concurrency vs Parallelism (multi-core)
- Covers
- Shared memory · Compiler optimization · CPU reordering · Visibility
- Related
- 2.2 Happens-Before · 2.3 Visibility · 2.5 Ordering · B2V3 Chapter 2 (JIT)
On this page
1Concept / Definition
The Java Memory Model is the part of the Java Language Specification (JLS Chapter 17, revised by JSR-133 for Java 5) that defines how threads interact through memory: which values a read of a shared variable is allowed to return. It exists because modern compilers and processors transform programs in ways that are invisible to a single thread but observable by others. The JMM gives programmers a simple contract — if the program is free of data races, it behaves as if all actions happened in one sequential interleaving — and gives compilers and hardware freedom to optimise everything else.

2Why It Exists
Without a memory model, concurrent Java programs would have platform-dependent behaviour: correct on one CPU, broken on another, broken after a JIT upgrade. Before Java 5, the original model was flawed (final fields could appear to change, volatile was too weak for common idioms). The JSR-133 model made Java one of the first mainstream languages with a precise, portable memory model — later influencing C++11's.
3Core Concepts
Shared memory
- All threads of a JVM share the heap: every instance field, static field and array element is potentially shared.
- Local variables and parameters live in thread-private frames and are never shared (though the objects they reference may be).
- The JMM talks about shared variables and actions on them: reads, writes, locks, unlocks, volatile accesses, thread start and join.
- A single thread always sees its own actions in program order (*as-if-serial* semantics).
Compiler optimization
- javac translates almost literally; the JIT (C1/C2, Volume III) performs the aggressive transformations.
- Legal single-thread transformations: keep a field in a register instead of re-reading memory, hoist loop-invariant reads out of loops, reorder independent stores, eliminate redundant reads and writes, merge or split accesses.
- Each transformation is invisible to the thread itself but can change what other threads observe.

CPU reordering
- CPUs execute out of order and buffer writes in per-core store buffers; loads may complete before earlier stores become visible.
- Caches are kept coherent per cache line, but the *order* in which different cores see writes to different variables can differ.
- x86 is relatively strong (only store-then-load reordering is visible); ARM and POWER are weak and reorder much more — code that 'works' on x86 laptops may fail on ARM cloud instances (2.5).

Visibility

The combined effect: without synchronisation, a write by one thread may become visible to another thread late, never (if the reader keeps a cached value), or in a different order relative to other writes. The JMM does not require immediate visibility; it requires visibility only along happens-before edges (2.2).
4How It Works Internally
The JMM is specified as a set of allowed executions: each read must see a write it does not happen-before-precede and that is not overwritten along happens-before, with additional causality rules that forbid 'out-of-thin-air' values. For implementers this translates into rules for the JIT (which reorderings are legal around volatile, locks and final fields) and into CPU fences emitted at those points (2.5). For programmers, the practical model is: establish happens-before between a write and every read that must see it.
5APIs / Features / Syntax
// Broken: may loop forever — JIT can hoist the read of 'running'
class Worker implements Runnable {
boolean running = true;
public void run() { while (running) { doWork(); } }
void stop() { running = false; }
}
// Correct: volatile creates happens-before between stop() and the loop's reads
class Worker2 implements Runnable {
private volatile boolean running = true;
public void run() { while (running) { doWork(); } }
void stop() { running = false; }
}
// (Or use interruption — Chapter 3 — or an AtomicBoolean.)6Practical Examples
| Symptom | Hidden cause | Fix |
|---|---|---|
| Background thread never stops after flag change | read hoisted out of loop | volatile flag / interruption |
| Config refresh ignored by some threads | plain field, no HB | volatile / AtomicReference |
| NullPointerException on a field set in constructor, only under load | unsafe publication, reordering | safe publication (2.3) |
| Counter lower than number of events | non-atomic increment (2.4) | AtomicLong / LongAdder |
| Works on dev laptop (x86), fails on ARM servers | weaker hardware ordering | correct synchronisation, not platform luck |
7Common Problems & Mistakes
- Believing that writes become visible 'eventually' by themselves.
- Using
Thread.sleeporSystem.out.printlnin tests, which accidentally add synchronisation and hide bugs. - Reasoning about hardware instead of the JMM.
- Assuming single-core behaviour on multi-core machines.
8Performance & Production Considerations
- The JMM lets the JIT optimise unsynchronised code fully; synchronisation costs are paid only where you ask for ordering.
- Concurrency bugs are timing-, load- and platform-dependent: they appear under production load or new hardware. Correctness must come from reasoning, not from tests.
The cost of ordering is concrete but usually small. A volatile read on x86 compiles to a plain load and a volatile write adds one fence, typically tens of cycles; on ARM, HotSpot uses load-acquire and store-release instructions. An uncontended lock is similarly cheap. What hurts is contention and false sharing: many threads writing the same variable or the same cache line make every core wait for ownership of that line, which is why LongAdder spreads updates across cells and why the JDK pads hot fields with @Contended. Measure hot paths with JMH or a profiler before replacing correct synchronisation with clever lock-free code.
For testing, use tools designed for the memory model rather than ordinary unit tests. OpenJDK's jcstress runs small concurrent actors millions of times on real hardware and reports which outcomes were observed, including the forbidden ones, and is worth running on ARM as well as x86. Code review, static analysis and race-aware design remain the primary defence.
9Architecture & Design Considerations
The JMM is the reason concurrency should be designed in, not patched in. Every piece of mutable state needs an explicit owner and a stated publication rule: confined to one thread, immutable after construction, guarded by a named lock, or held in a concurrent structure whose documentation states its happens-before guarantees. Writing that rule into class documentation turns a subtle memory-model question into a reviewable design decision.
At architecture level, the safest systems minimise shared mutable memory altogether. Request-scoped objects in a thread-per-request or virtual-thread server, immutable records and value objects, message passing through queues or executors, and stateless services that keep shared state in a database or cache all reduce the surface where the JMM must be reasoned about by hand. When low-level code is genuinely required, such as a custom cache or a lock-free buffer, isolate it in a small, well-tested library with jcstress tests, rather than spreading volatile fields across business code.
Treat the hardware as a variable. Fleets increasingly mix x86 and ARM instances, such as AWS Graviton, so correctness must follow from the JMM rather than from the platform the code was first tested on.
10Interview Questions & Answers
What is the Java Memory Model?
The Java Memory Model is the part of the Java Language Specification, chapter 17, rewritten by JSR-133 for Java 5, that defines how threads interact through shared memory. It specifies which values a read of a shared field or array element is allowed to return in a multithreaded program, and which actions, such as volatile accesses, locking, thread start and join, and final-field initialisation, create ordering and visibility guarantees through happens-before. Its central promise is that a correctly synchronised, data-race-free program behaves as if it ran in one sequential interleaving. Everything outside that contract is left free for the JIT and the CPU to optimise, which is why it exists.
Why can one thread fail to see another thread's write?
Because several layers are allowed to delay or reorder the write as long as a single thread cannot tell. The JIT may keep a field in a register, hoist a read out of a loop or reorder independent stores, so the reader may never reload the value from memory. The CPU executes out of order and parks stores in a per-core store buffer before they reach the cache, so other cores see them late or in a different order. The classic symptom is a stop flag that a worker thread never notices. Without a happens-before edge, such as a volatile write and read or a shared lock, none of this is forbidden.
What does 'data-race-free programs are sequentially consistent' mean?
It is the JMM's main guarantee to programmers. A data race exists when two threads access the same variable, at least one access is a write, and the accesses are not ordered by happens-before. If a program has no data races in any sequentially consistent execution, then every execution will appear sequentially consistent: as if all actions from all threads ran in one global order that respects each thread's program order. The practical consequence is that, once shared state is properly protected by locks, volatile, atomics or safe publication, you can reason about the code by interleaving, and reorderings by the JIT and CPU become invisible. Racy programs get only weak guarantees.
Why might concurrent code work on x86 but fail on ARM?
Because x86 has a strong hardware memory model that hides most reorderings, while ARM allows far more. On x86 the only reordering visible to software is a later load passing an earlier store to a different address, so code with missing synchronisation often appears to work. ARM and POWER may reorder loads with loads and stores with stores, so a reader can see a flag set before the data it guards, or see a reference to a partially constructed object. The JIT can break such code anywhere, but ARM exposes it more often. As fleets move to Graviton and other ARM instances, latent races surface, which is why correctness must come from the JMM.
How should teams approach concurrency correctness given the JMM?
Make happens-before explicit by design instead of hoping the hardware cooperates. Start by reducing shared mutable state: prefer immutable objects and records, confine state to one thread or request, and communicate through executors, queues and concurrent collections whose documentation states their guarantees. Where sharing is unavoidable, choose one mechanism per piece of state, a lock, a volatile field or an atomic, and document it. Review publication of objects across threads, keep lock-free code in small, well-owned libraries tested with jcstress, and run concurrency tests on ARM as well as x86. Treat passing tests as weak evidence only, since races are timing-dependent, and rely on reasoning and reviews instead.
Test your knowledge on this topic →Flashcards from this topic's 5 questions, filtered by level and type.