Lesson · Java Memory Model (JMM)
Memory Architecture: the hardware the JMM talks to
15 min readMemory Architecture
The runtime map says where a value lives. This lesson goes one layer down, to the machine that executes the bytecode: caches, store buffers, out-of-order execution and the compiler. Every rule in the Java Memory Model exists because of what that machine is allowed to do.
One layer below the runtime map
memory-model-basics drew the runtime map: per-thread stacks, a shared heap, and objects kept alive by reachability. That map tells you where a value is declared to live. It says nothing about the journey a write takes, and the journey is where visibility bugs come from.
This lesson stays at the hardware layer. Below the bytecode there are registers, store buffers, caches and reordering, and the Java Memory Model exists to bound what a program is allowed to observe on top of them. No new syntax here; this is the machine the next two lessons keep referring to.
The runtime map answers where a value lives. This layer answers when a write becomes visible, and the honest answer is never 'the moment the instruction retired'.
The path of a write
A store does not go to main memory. It enters the core's store buffer first, then lands in that core's L1 cache, and only later may it reach L2, the shared L3 cache, and DRAM.
Reads make the same journey in reverse and usually stop early: a core reads from its own cache and consults the rest of the machine only on a miss. Memory is a hierarchy of copies, and every copy is allowed to be the one some core sees.
Data moves in cache lines, typically 64 bytes, so variables that sit near each other in memory travel together and one transfer can carry several of them.
- Registers. Where the operation actually happens. Private to the core, shared with nobody.
- Store buffer. Where a store waits before it enters the cache. A core reads its own recent stores from here, which is why your own writes never look late to you.
- L1 and L2. Per-core caches: fast, private, and the source of most reads.
- L3. Shared by the cores on the socket, and the first place where two cores routinely meet.
- DRAM. Main memory, the slowest hop by a wide margin. Every level above it is a copy.
A write is a journey with several stops, and the reader meets whichever copy its own path reaches.
Coherence: one address, kept honest
With several copies of every location, something has to stop them disagreeing. Cache coherence is that protocol, usually implemented as MESI: each cache line is Modified, Exclusive, Shared or Invalid, and a core must hold a line exclusively before writing it, which forces the other copies to drop theirs.
The guarantee is narrow, and worth stating precisely: coherence is about one address. All cores agree on the order of writes to a single location, and no read returns a value that was never written to it. Nothing in the protocol orders writes to two different addresses.
Two mechanisms then break an assumption you never knew you were making. A store waits in a per-core buffer before it enters the cache, and out-of-order execution lets later work proceed while an earlier store is still pending. Neither is a coherence violation; both are reorderings a Java program is allowed to observe.
Coherence keeps one address honest; it says nothing about the order of two addresses.
The store buffer, seen from the other core
Put two writes in program order. Core 1 executes X = 1 and then Y = 1, and each store enters its own store buffer. If the buffer lets them through independently, core 2 can observe Y = 1 while X still reads the old value, even though every instruction on core 1 ran in the order that was written.
Honesty about hardware: x86 is a strong model and keeps stores from one core in that order, so this particular inversion does not show up there. x86 still allows a load to pass an earlier store to a different address, because that store is still sitting in the buffer. ARM and POWER relax more, and Java has to run on them too.
That is why the JMM is written for the weakest machine that can run Java. A rule that held only on x86 would make one build correct on a laptop and wrong on a phone, so the contract permits what the weak models permit, then sells primitives that remove the reorderings.
- Core 1 executes
X = 1. The store enters its store buffer, and other cores still see the old value of X. - Core 1 executes
Y = 1. Both stores are now pending. Program order said X before Y; that is the only claim the program made. - The two buffered stores drain independently. Y reaches the shared view while X is still pending.
- Core 2 reads X and then Y, and sees the old value for X and the new value for Y: the writes became visible in the opposite order to the one they were issued in.
- Now place a store barrier between them. The buffer may not pass a barrier, so
X = 1must be visible beforeY = 1is let through, and the reader sees both new values in write order.
If a reader can see two writes in the other order, the writes were allowed to travel separately. A barrier is the instruction that re-couples them.
Store buffer lab · two cores, one shared view
write on core 1, drain, then read on core 2store buffer · waiting to enter the cache
The reads have no ordering power of their own: they report whichever copies are reachable.
shared view · L3 and DRAM, what the other core can reach
Core 1 is about to issue two writes in program order. Watch the order in which they reach core 2.
accent = core 1, violet = core 2, amber = a store still waiting in the buffer. The drain order shown here is what the JMM has to permit: x86 keeps these two stores in order, ARM and POWER may not, and Java has to be correct on all three.
The reordering a compiler is allowed to do
Hardware is only half of the story. The compiler and the JIT reorder as well, under a rule that sounds harmless: a single thread must not be able to tell the difference. The specification requires each thread to observe its own actions as if it ran alone, and that is the only constraint on a transformation.
Take an unguarded flag. Nothing in the loop below writes stop, so a read of stop on every iteration may legally be lifted out of the loop: for a single thread the result is the same, and the thread that writes stop = true cannot see a difference either.
static boolean stop; // plain field: no visibility promise void waitForStop() { while (!stop) { // the JIT may hoist this read out of the loop doWork(); // nothing here writes stop, so the read is invariant } }
An unguarded read can be hoisted out of the loop that was supposed to wait for it.
Why the JMM exists
The hardware offers reordering; the JMM is the contract that says which reorderings a Java program is allowed to observe. It describes no registers and no buffers. It defines the set of legal behaviours and names the primitives that take reorderings off the table.
Ordering is the product each primitive sells. Mutual exclusion is the part everyone remembers first: synchronized also guarantees that a later lock on the same monitor sees every write the previous unlock published, and volatile orders accesses to a single field across threads.
- `volatile` orders reads and writes of one field and makes them visible. It adds nothing for compound actions such as
count++(see race-conditions and the volatile lesson). - `synchronized` makes every access inside the block visible to the next thread that locks the same monitor, with mutual exclusion as the side effect.
- Atomics and `VarHandle` order accesses and, for read-modify-write operations, also remove the interleaving.
- `final` fields get a construction-time guarantee that other fields do not (forward link: final-field semantics).
Hardware reorders, the JMM bounds what you can observe, and the primitives are the opt-out.
Hardware stack · registers to DRAM
one write, several places it can waitregisters
where the operation happens, private to the core
store buffer
a store waits here before the cache, and later work proceeds meanwhile
L1 and L2
per-core copies, cache lines of typically 64 bytes; most reads stop here
registers
where the operation happens, private to the core
store buffer
a store waits here before the cache, and later work proceeds meanwhile
L1 and L2
per-core copies, cache lines of typically 64 bytes; most reads stop here
cache coherence (MESI)
Each cache line is Modified, Exclusive, Shared or Invalid, and a write must own its line. One address stays consistent for every core: reads never return a value that was never written. The promise stops at the single address, so the order between two addresses is not covered here.
L3 cache
shared by the cores on the socket: the first place two cores routinely meet
DRAM
main memory, the slowest hop by a wide margin; every level above it is a copy
x86, ARM, and a deliberately conservative contract
Three families, one contract. The table stays qualitative on purpose: the question is which class of machine each primitive has to satisfy, not who is faster.
| Hardware | Stores from one core | What else is allowed | What it means for Java |
|---|---|---|---|
| x86 and x86-64 | become visible in order | a load may pass an earlier store to a different address | strong: innocent-looking code works here, which is how a race survives until it meets a weaker CPU |
| ARM | may become visible in either order | load-load, load-store and store-store reordering as well | barriers (typically DMB) are required, and the JMM must permit everything this machine can do |
| POWER | may become visible in either order | similarly weak, with its own barrier instructions such as lwsync and sync | same conclusion: the JMM is written for the weakest member of the family |
Strong hardware never grants extra guarantees. It hides the ones your code failed to ask for.
What this layer hands to the rest of the part
Four facts to carry forward, each of which becomes a failure with a name in the next lesson.
- A write is a journey: register, store buffer, cache, shared memory, with the reader meeting whichever copy its own path reaches.
- Coherence is per address: the protocol keeps one location consistent and says nothing about two.
- Order between two writes can invert on the hardware Java must support, unless a barrier re-couples them.
- The compiler reorders too: as-if-serial licenses hoisting, which is how an unguarded wait loop spins forever.
- The JMM bounds all of it, and the next two lessons name the failures it exists to fix and the single rule it sells.
The JMM exists because the hardware that runs Java is weaker than the code you wrote.
Coherent does not mean ordered
The trap opens with a true sentence: caches are coherent, so a thread never reads a value that was never written. The conclusion people draw from it is false, that writes appear where and when the code expects them. Coherence is a promise about a single address, kept per cache line. It does not order writes to different addresses, it does not stop a store from waiting in a store buffer, and it does not stop the JIT hoisting an unguarded read out of a loop that has been reading the same field forever. If two threads need an order between two writes, a plain field never provides one. `volatile`, `synchronized` or an atomic does.
Interview angles
Why can a write from one thread stay invisible to another, even on a normal multi-core CPU?+
Because the write can still be sitting in the writer's store buffer or in a cache the reader never consults, and because the reader's load may have been hoisted out of its loop. The JMM requires visibility only where a happens-before edge connects the two threads.
Coherence then keeps the mechanical part honest: no reader ever obtains a value that was never written. What is missing is an order between the observer and the event, and the primitives are what supply it.
Follow-up: Which primitive would you reach for, and what exactly does it change?
What does cache coherence guarantee, and what does it not?+
It keeps all copies of one address consistent: cores agree on the order of writes to that address, and a read never returns a value that was never written to it. It guarantees nothing about the relative order of writes to two different addresses, which is why store buffers and out-of-order execution can invert what a reader observes.
Common misconception: That coherence is the same thing as ordered visibility. It is single-address consistency, which is a much smaller promise than the one people hear in the word.
How can `while (!stop) {}` spin forever after another thread sets `stop = true`?+
Two independent causes. The JIT may hoist the read of stop out of the loop, because nothing in the loop writes it and a single thread could not tell. And even a reloaded read may miss the write, because the store may not have become visible. volatile on stop closes both: every read consults the field, and the write is visible to any later read of it.
static volatile boolean stop; // the read stays in the loop, and the write is visible
Common misconception: That the loop needs a sleep, or that the field is safe because it is small and static. The bug is the missing guarantee, not the busy waiting.
Why does the same program work on x86 and fail on ARM?+
x86 is a strong model: stores from one core become visible in order, and loads behave as acquires, so many reorderings the JMM permits do not appear there. ARM and POWER reorder more aggressively and need explicit barriers. The JMM is written for the weakest machine, so the program is wrong everywhere; a strong CPU merely fails to reveal it.
That is also why you cannot normally reproduce this class of bug on a desktop: it is a property of the hardware you did not run on, which is why tools such as jcstress exist, and why removing the race beats reproducing it.
Follow-up: So how would you test for this class of bug, if at all?
Does `volatile` flush a value to main memory?+
No, and the JMM never says where a value lives. It says what order is preserved and what visibility is owed. Implementations keep the value in cache and use barriers (a fence-like instruction on x86, a DMB on ARM) to hold the required order, while coherence handles the rest.
Common misconception: That a volatile write is a write to RAM. There is no per-field flush to perform; the obligation is ordering and visibility, not a trip to DRAM.
What is the primary guarantee `synchronized` sells?+
Ordering and visibility across the monitor, with mutual exclusion as the familiar side effect. An unlock publishes every write made before it to the next thread that locks the same monitor, and the accesses inside the block behave as one ordered unit.
JLS 17.4 defines the happens-before order, and the monitor rule is one of its edges. The happens-before lesson later in this part walks the chain link by link.
Follow-up: Where is that chain defined formally?