Volatile & JMM: The Visibility Bedrock of Java Concurrency — From Bugs to Barriers
This article explores Java Memory Model (JMM) and volatile through three real production incidents, explaining visibility, ordering, and atomicity guarantees, happens-before rules, memory barriers, and practical patterns like safe publication and double-checked locking, with a four-question checklist and eight-point code review guide.
Reading font

Three Production Incidents
The article opens with three real-world visibility bugs:
Config switch ineffective for 40 minutes : A risk system used a plain boolean switchFlag. The callback thread set it to true, but the consumer loop while (!switchFlag) had the field hoisted to a register by JIT, so it never saw the update. Fixed by adding volatile.
DCL singleton occasional NPE : A payment system used double-checked locking without volatile on the instance field. The write order allocate → initialize → assign reference was reordered to allocate → assign reference → initialize, so another thread could see a non-null reference to a partially constructed object.
Volatile counter undercounts 0.7% : An ops team used volatile long count for high-concurrency counting. Under load, two threads read the same value, both incremented, and wrote back the same result, losing updates. Switching to AtomicLong eliminated the discrepancy.
Why JMM Exists: Three Properties and Default Invisibility
JMM (JSR-133) defines a hardware-agnostic abstraction: each thread has a working memory, shared variables live in main memory, and JMM rules govern when writes flush and reads reload. MESI is merely one implementation strategy on x86, not JMM itself.
JMM guarantees three properties:
Atomicity : Single reads/writes of primitives (except long / double on 32-bit) are atomic; compound ops like i++ are not.
Visibility : A thread's write becomes visible to others only with synchronization (default: no guarantee).
Ordering : Code order is not guaranteed across threads; compiler, JIT, and CPU may reorder as long as single-thread semantics ( as-if-serial ) hold. synchronized</strong> covers all three; <code>volatile covers visibility and ordering only.
Volatile Semantics: Visibility and Reordering Prevention
volatileprovides two guarantees:
Visibility : A write flushes to main memory and is immediately visible; a read reloads from main memory, bypassing local cache. Effectively, writes broadcast, reads force-listen.
Ordering : JMM inserts memory barriers around volatile accesses: before a volatile write, a StoreStore barrier; after, a StoreLoad barrier. Before a volatile read, a LoadLoad barrier; after, a LoadStore barrier. StoreLoad is the most expensive barrier (full fence). On x86 it is implemented with a lock prefix instruction. Volatile write pays one full barrier; volatile read on x86 is nearly free (ordinary mov) because x86's TSO model only allows Store-Load reordering.
Cost profile: volatile write adds one barrier instruction, volatile read adds one cache-coherency transaction — nanoseconds, far cheaper than a lock. The key is its promise boundary: visibility and ordering only, no atomicity, no mutual exclusion, no blocking.
Happens-Before: The Sole Concurrency Correctness Arbiter
Happens-before (hb) is a partial order: if A hb B, A's result is visible to B and A precedes B. Eight rules:
Program order (single thread)
Monitor lock (unlock hb subsequent lock)
Volatile (write hb subsequent read)
Thread start ( start() writes visible to new thread)
Thread join (thread's writes visible after join() returns)
Thread interrupt ( interrupt() writes visible to interruption check)
Object finalization (construction hb finalize())
Transitivity
Usage: to verify correctness, draw hb chains. No hb = data race = no guarantee. Hb is not temporal order; it is a visibility promise established by synchronization actions.
Rules ② and ③ underpin synchronized and volatile. Rules ④–⑥ explain why thread APIs safely pass data. Rule ⑦ plus final field semantics enable safe publication of immutable objects.
Atomicity Boundary: What Volatile Cannot Do
volatiledoes not make compound actions atomic. i++ is read-modify-write; volatile ensures each step sees the latest value but does not prevent interleaving. Two threads reading 100, both writing 101, loses one update.
Counter selection by contention:
AtomicLong : CAS spin, low-to-medium contention.
LongAdder : Striped Cell[] array, high contention, throughput scales; read is approximate (fine for metrics, not for accounting).
synchronized : Multi-variable invariants (e.g., okCount + failCount == total).
Four-question checklist for volatile suitability:
Write independent of current value? (flag yes, counter no)
Variable independent? (no multi-field invariant)
Multiple writers unordered acceptable? (else CAS/lock)
Only visibility needed, no mutual exclusion? (else lock)
All four must be "yes" to use volatile.
Production Templates
5.1 State Switch & Graceful Shutdown
public class GracefulShutdown {
private volatile boolean running = true;
public void shutdown() { running = false; }
public void run() {
while (running) {
Message msg = poll();
if (msg != null) handle(msg);
}
flush();
}
}Flag volatile + direct read in loop condition. No local caching of flag. Cleanup after loop.
5.2 Safe Publication: Immutable Config Object
public final class RiskConfig {
private final int threshold;
private final boolean enabled;
private final List<String> rules;
public RiskConfig(int threshold, boolean enabled, List<String> rules) {
this.threshold = threshold;
this.enabled = enabled;
this.rules = List.copyOf(rules);
}
}
// Publisher
private volatile RiskConfig config;
public void update(RiskConfig c) { this.config = c; }Multiple fields bundled into immutable object (all final, defensive copy). Single volatile reference publish ensures readers see either old or new config, never a torn mix.
5.3 Correct DCL Singleton
public class Singleton {
private static volatile Singleton instance;
public static Singleton get() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}Volatile prevents reordering of initialization and reference assignment. First check avoids lock contention. Preferred alternatives: static holder class or enum singleton.
5.4 Counter Selection
// Low/medium contention
private final AtomicLong count = new AtomicLong();
public void inc() { count.incrementAndGet(); }
// High contention
private final LongAdder total = new LongAdder();
public void add(long x) { total.add(x); }
// Multi-variable invariant
private long okCount, failCount;
public synchronized void record(boolean ok) {
if (ok) okCount++; else failCount++;
}Core Source Code Insights
1. ACC_VOLATILE Bytecode Flag
Volatile appears only as ACC_VOLATILE (0x0040) on the field. Read/write bytecodes ( getfield / putfield) are identical to ordinary fields. JVM interprets the flag at access points: interpreter uses special instructions, JIT inserts barriers. Hence volatile is an access-point semantic, not a field semantic. Local variable caching bypasses volatile because it's not a shared-field access point.
2. x86 StoreLoad Implementation
mov %eax, 0x10(%rbx) // store
lock addl $0x0,(%rsp) // StoreLoad barrierlockprefix locks the cache line, makes write globally visible, and prevents reordering. Volatile read on x86 is a plain mov.
3. Unsafe's Three Write Semantics
// putIntVolatile: full semantics (StoreStore + store + StoreLoad)
// putOrderedInt: release semantics (omits StoreLoad, faster)
// JDK 9+ VarHandle: getOpaque < getAcquire < getVolatileAQS uses putOrderedInt for node linkage (ordering only, visibility later ensured by CAS full fence). VarHandle exposes fine-grained control; daily code uses getVolatile.
4. AQS's Volatile State
public abstract class AbstractQueuedSynchronizer {
private volatile int state;
protected final int getState() { return state; }
protected final void setState(int newState) { state = newState; }
// compareAndSetState uses Unsafe.compareAndSwapInt
}AQS combines volatile visibility (hb rule ③) with CAS atomicity to build all JUC synchronizers.
Seven Cost Accounts
Visibility cost : nanoseconds vs. 40-minute outage — highest ROI.
Ordering cost : write pays full barrier, read cheap; write-heavy flags still negligible.
Atomicity misuse cost : volatile counters lose updates (0.7% in test) — four-question gate prevents this.
Safe publication cost : immutable object + volatile ref same code size as per-field volatile, simpler mental model.
Cognitive cost : JMM is spec, not hardware doc; reason via hb rules, not cache metaphors.
Monitoring cost : visibility bugs have no exceptions, logs, or metrics — defense is load-test reconciliation and code-review checklist.
Ecosystem cost : entire JUC (AQS state, atomic values, concurrent maps, thread pool ctl) rests on volatile semantics.
Code Review Checklists
Four-Question Volatile Gate (all must be yes): write independent? variable independent? multi-writer unordered ok? only visibility needed?
Eight-Point Volatile Physical (one veto fails) :
Required volatile flags present? (loop conditions, shutdown flags, config refs)
No compound ops on volatile? ( i++, check-then-act)
Variable truly independent? (no multi-field invariant)
Multi-field state uses safe publication? (immutable + volatile ref)
DCL instance has volatile?
Immutable class fields all final?
Flag cached in local variable? (bypasses re-read)
Better tool available? (AtomicLong, LongAdder, lock)
20 Interview Questions (with Answers)
Covers JMM definition, visibility root cause, three properties mapping, volatile semantics, memory barriers, hb eight rules, hb vs time, DCL volatile necessity, DCL alternatives, volatile i++ failure, long/double tearing, four-question checklist, volatile vs synchronized, three reordering layers, as-if-serial, final field semantics, volatile in AQS, MESI vs JMM, visibility bug triage.
One-Page Cheat Sheet
Ten takeaways: JMM spec abstraction; three properties default unguaranteed; volatile write=broadcast read=force-listen; StoreLoad costliest; hb eight rules sole judge; hb ≠ time; volatile no atomicity; four-question gate; multi-field = immutable + volatile ref; DCL volatile prevents init-assignment reorder; prefer holder/enum.
Next Episode Preview
Next: AQS & Lock — how ReentrantLock builds tryLock/fair/Condition from a volatile int state + CAS + CLH queue, acquire/release flow, fair vs non-fair difference, and when to upgrade from synchronized.
For questions about attribution, corrections or content rights, please contactand we will review it promptly.