Lesson · Java Memory Model (JMM)
Visibility, Atomicity and Ordering: the three failures the JMM exists to fix
15 min readVisibility, Atomicity & Ordering
Three different failures hide behind the phrase 'it is a threading bug': a write nobody sees, an action that splits in half, and writes that arrive in the wrong order. Each has its own cause and its own fix, and mixing them up is how the wrong primitive gets applied to the wrong bug.
Three failures, not one
When concurrent code misbehaves, the symptom usually repeats: a value that should have changed did not, or changed into something impossible. The cause is one of three failures, and they are easy to confuse because all three produce a stale or wrong value.
Visibility asks whether a write ever reaches the reader. Atomicity asks whether an action can be split in the middle and observed half-done. Ordering asks what order independent operations become visible in. Each has a different machine-level cause and a different Java primitive that removes it, so the table below is the map for the whole lesson.
| Failure | What goes wrong | Java rule that fixes it | The primitive |
|---|---|---|---|
| Visibility | a write stays in a store buffer or in a cache the reader never consults; a read can also be hoisted out of a loop | an ordered access to the same field or monitor | volatile, synchronized, atomics |
| Atomicity | a read-modify-write interleaves, or a 64-bit value is read as two 32-bit halves | one indivisible operation, or an ordered 64-bit access | synchronized, atomics, and volatile for long and double |
| Ordering | independent writes become visible in the opposite order, so a reader sees a half-built state | an order between the actions: nothing before the write may be observed after it | volatile, synchronized, final fields for construction |
Different cause, different fix. 'Threading bug' is not a diagnosis; it is the start of one.
Visibility: the write nobody saw
A plain field carries no visibility promise at all. A write may sit in the store buffer or in the writer's cache, and nothing requires another thread to ever see it. A read may be served from a stale copy, or hoisted out of the loop that contains it, as the hardware lesson showed.
The classic shape is a flag: one thread sets stop = true, another spins on while (!stop). Without synchronization the loop is allowed to run forever, and on a real machine it sometimes does. A field read repeatedly inside a loop that never writes it is a hoisting candidate for exactly the same reason.
static boolean stop; // plain: no visibility, no ordering Thread worker = new Thread(() -> { while (!stop) { // may be hoisted: nothing in this loop writes stop doWork(); } }); worker.start(); stop = true; // allowed to go unseen by the worker
- The fix is any ordered access: mark the flag
volatile, guard both sides with the same monitor, or keep the state in an atomic. - Ordering, not speed:
volatiledoes not make the write travel faster; it removes the licence to reorder and the licence to keep serving a stale copy. - Scope is one field: an unguarded field next door keeps its own story, so visibility has to be arranged per field or per guarded block.
- Compound actions:
volatiledoes not makecount++atomic, which race-conditions covers in full (forward link: the volatile lesson).
Visibility is the promise that a write reaches a reader. Nothing about a plain field makes that promise; a primitive has to.
Atomicity: the action that splits in half
Atomicity is about indivisible actions. race-conditions already owns the everyday case, where i++ splits into LOAD, ADD and STORE and two threads lose a write. This section takes the part that surprises people even after they know that, because it lives in the specification rather than in the timing.
The JLS permits reads and writes of a non-volatile long or double to be treated as two separate 32-bit operations. A reader can therefore observe the first half of one write and the second half of another: a torn value, one that no thread ever wrote.
static long total; // non-volatile: the spec may split this into halves total = 1L; // halves: 00000000 | 00000001 total = -1L; // halves: FFFFFFFF | FFFFFFFF long seen = total; // a concurrent reader may combine what it observed // and see 0xFFFFFFFF00000001, written by nobody static volatile long safe; // volatile: one atomic 64-bit access, always
- Non-volatile `long` and `double` may tear: JLS 17.7 treats a single write as two 32-bit halves, so a concurrent read can mix halves from different writes.
- `volatile long` and `volatile double` are always atomic: the access is read and written as one unit (JLS 17.7).
- Everything narrower is already atomic: reads and writes of
int,booleanand the rest are single actions, and references are atomic regardless of their width. - Word tearing is forbidden, not merely discouraged: JLS 17.6 requires each field and array element to be distinct, so two threads updating adjacent
byteelements of one array cannot disturb each other.
Torn `long` and `double` are where the specification and your machine disagree: 64-bit HotSpot is atomic in practice, and only `volatile` makes it a promise.
Ordering: the writes that arrive shuffled
The third failure survives a successful visibility fix. Two writes, each made properly visible, can still become visible to a reader in the opposite order to the one the writer used. Nothing is lost and nothing is split: the order is simply not part of the promise unless something creates it.
Synchronization has the same one-way shape, and practitioners describe it with the roach motel metaphor: reads and writes may be moved into a synchronized region, but not out of it. That asymmetry is why an unlock can publish everything written before it, and why guarded initialization cannot sneak past the unlock that releases it.
Two consequences appear in real code. A flag written before its data can become visible before the data, so a reader acts on state that is not there yet. And a field written inside a constructor has no guarantee of being visible to another thread that sees the reference, which is the unsafe publication case two sections down.
No chain, no order: if nothing connects two writes, either order is allowed, and the reader may pick the inconvenient one.
Unsafe publication: the half-built object
A constructor writes fields, then the caller publishes the reference. Every step is correct in isolation, and another thread that reads the reference is still allowed to see the field in its default state, because nothing ordered the constructor's write before the reader's read.
The failure is invisible in single-threaded tests and in most concurrent ones: the window is narrow and the strong hardware you develop on does not widen it. It is the reason double-checked locking needs volatile, and the reason the final-field rules exist at all.
class Holder { int n; // not final: no construction guarantee Holder(int value) { n = value; } } static Holder holder; holder = new Holder(42); // the reference is published from here // in another thread, later: Holder h = holder; // reading the reference succeeds: non-null int n = h.n; // may still read the default 0
- The fix is a chain: publish the reference through a
volatilefield or a monitor, so the reader's access has an order against the constructor's writes. - `final` fields are the other answer: a correctly constructed object's final fields are visible to any thread that sees the reference, and that rule lives in the final-field lesson.
- One rule matters here: the reference must not be visible to other threads before the constructor finishes, or the guarantee has nothing to attach to.
You did not publish the object; you published a promise the other thread cannot keep.
Scenario lab · one failure at a time
pick a failure, then flip the fixT1 · setter
stop = true;
T2 · worker
while (!stop) { work(); }
outcome without a fix
The worker keeps spinning. Nothing orders its read against the write, and the read may be hoisted out of the loop entirely.
Matching the primitive to the failure
Every fix in this lesson is one of a few primitives doing the same job at different strengths. Choose by asking which failure you have, not by which keyword feels familiar, and remember what the chosen primitive leaves in place.
| Primitive | What it orders | Failures it removes |
|---|---|---|
volatile field | accesses to that one field; everything written before the volatile write is visible to a reader that sees it | visibility and ordering for one field, plus atomic 64-bit access for long and double |
synchronized block or method | every access inside the block; an unlock publishes everything before it to the next lock of the same monitor | visibility, ordering, and atomicity for the compound actions on the guarded state |
atomic classes and VarHandle operations | accesses to the one variable, with read-modify-write operations that cannot be interleaved | visibility, ordering and atomicity, without blocking |
final field | the constructor's writes are visible to any thread that sees the reference after construction | the half-built object case, for that field only |
- Name the symptom: a stale value (visibility), an impossible value or a lost update (atomicity), or a half-built state (ordering).
- Find the shared mutable state and every access to it. If there is exactly one field and the operation is a plain read or write,
volatileis the smallest fix. - If the operation is compound,
volatilealone is not enough: usesynchronized, an atomic, or restructure so a single operation owns the state. - If one field guards others, order the pair: write the data first, then flip the flag whose access is ordered, and read the flag before the data on the other side.
- If the state is an object built once, make its fields
finalwhere possible, and publish the reference through an ordered access.
Pick the primitive that removes the failure you have, and know what it leaves untouched.
What to remember
The three failures stack rather than replace each other, and the vocabulary is what makes the difference in conversation. Say which one you mean, and the fix usually names itself.
- Visibility is when you see the write; atomicity is whether the action can be split; ordering is what order your writes arrive in.
- Fix order matters: ordering survives a visibility fix, and atomicity survives both, which is why one keyword rarely repairs a design.
- Torn `long` and `double` are permitted by the spec and removed by
volatile, while word tearing is forbidden outright. - A racy program can pass every test you run, because the JMM allows the correct interleaving too. The next lesson replaces symptoms with a rule: happens-before tells you when a write must be seen.
Three failures, three fixes, one rule behind all of them, and that rule is next.
Three failures · one panel each
each panel: what the writer does, what the reader gets, and the edge that is missingno edge: the read keeps serving the old copy
the primitive that orders it
volatile, synchronized, or an atomic
the loop spins forever, and the write is simply not part of the reader's world.
no atomic access: two 32-bit halves can mix
the primitive that orders it
volatile long, or a monitor
the reader holds a value that neither writer ever stored, and no thread is at fault.
no edge: the publication arrives before its contents
the primitive that orders it
a chain (volatile or monitor), or final fields
the reference is valid and the object behind it is half-built: the classic unsafe publication.
Two threads, one symptom, two different fixes
The pressure in a live debugging session is to pick a primitive and move on, and these three failures will not let you. A stale flag needs visibility: `volatile` on the flag. A compound update needs atomicity: a monitor or an atomic, not `volatile`. A half-built object needs an order between construction and publication: a chain, or `final` fields. A program can also have one of each at the same time, which is why 'add volatile everywhere' produces code that is slower, still wrong, and harder to reason about. Name the failure first, then choose.
Interview angles
What is the difference between a visibility problem and an ordering problem?+
Visibility asks whether a write is ever seen by another thread; ordering asks what order two visible operations take. A reader can see two writes and still see them in the wrong order, and the two often share one fix because a single primitive tends to supply both.
Is a `long` write atomic?+
Not by specification, unless the field is volatile. JLS 17.7 permits a non-volatile long or double to be written and read as two 32-bit halves, so a reader can observe a torn value. A volatile long is always atomic, and 64-bit HotSpot happens to be atomic in practice anyway.
The rule exists for the 32-bit implementations of the world. The specification keeps the permission rather than promising something a small virtual machine cannot deliver, which is exactly why the fix is a keyword and not a hardware assumption.
What is word tearing, and does the JLS allow it?+
Word tearing is observable interference between distinct fields or array elements, such as a write to a[1] disturbing a[0]. JLS 17.6 forbids it: each field and array element must behave as distinct, and Java bytecode has byte-wise array instructions precisely so a virtual machine can honour that on hardware with wider access.
Common misconception: That word tearing and long tearing are the same problem. Word tearing is adjacent elements interfering with each other, which is forbidden. Torn long and double are one value observed in halves, which is permitted for non-volatile fields.
What does the roach motel metaphor describe?+
The one-way nature of synchronization: reads and writes may be moved into a synchronized region but never out of it. That is why an unlock publishes everything written before it, and why guarded initialization cannot be observed past the unlock that released it.
How can another thread see a non-null reference and a default field value?+
Because seeing the reference is only seeing the reference. Without a happens-before edge from the constructor's writes to the reader's read, the reader may see default values for non-final fields. That is unsafe publication.
The fixes are to publish through an ordered access (a volatile field, a monitor) or to make the field final, which carries its own construction guarantee. In both cases the reference must not be visible to other threads before the constructor finishes.
Follow-up: Where are the final-field guarantees specified?
Why does a data race not always produce a wrong answer?+
Because the JMM is a permission system, not a requirement system: it allows the correct interleaving along with the broken ones. A passing test proves that one execution was legal, not that the program is race-free, which is why the reasoning tool is the rule in the next lesson rather than a stress loop.