Lesson · Java Memory Model (JMM)
volatile: visibility and ordering, never atomicity
15 min readvolatile
A volatile field is a fence, not a lock: a write to it happens-before every later read of it, and neither access can be reordered across the fence in the forbidden direction. What the keyword never does is make a compound action like count++ atomic, and knowing exactly where that line falls is most of what volatile knowledge is.
The flag that never stops
A worker loop runs until a flag flips, and the flag is an ordinary field. The thread that sets it runs, prints nothing, and the worker keeps spinning: the program never terminates.
Nothing failed at the CPU level. The reader was allowed to keep reading a stale value, and the JIT was allowed to hoist the field read out of the loop, because nothing in the program ever told the compiler those two threads had an agreement. A plain field carries no promise that a write on one thread is ever seen on another.
class Worker implements Runnable { private boolean stop = false; // plain field: no agreement between threads void shutdown() { stop = true; // main writes true, and hopes } public void run() { while (!stop) { // may read a stale value, or hoist the read once Thread.onSpinWait(); // spin politely instead of burning a core } } }
Predict the fix before reading on. The bug is not in the loop condition and not in the write; it is the missing agreement. One keyword creates that agreement, and the rest of this lesson is what it does and does not buy.
The two guarantees
The language specification gives volatile fields a happens-before edge: a write to a volatile field happens-before every subsequent read of that field (JLS 8.3.1.4). Happens-before is a visibility promise: the reader is guaranteed to observe the stored value, not a stale copy from a core-local cache.
The second guarantee is ordering, and it is directional. A volatile write is a release: everything the writing thread did before it stays before it. A volatile read is an acquire: nothing the reading thread does afterwards moves above it. Actions cannot move out past the fence. This is the roach motel picture: operations may be reordered among themselves on each side, but they cannot cross the barrier in the forbidden direction.
| Access | What may not cross it |
|---|---|
| volatile write (release) | Earlier reads and writes of that thread cannot move below the write. |
| volatile read (acquire) | Later reads and writes of that thread cannot move above the read. |
A volatile access is a fence with a direction. Reads and later actions stack above an acquire; earlier actions and the write itself stack below a release; and the write-to-read edge is the bridge between the two threads.
volatile · the fence and its directions
operations may reorder on each side; they cannot cross the fencethread 1 · writer
volatile write · flag = true
release: everything above this line cannot sink below it
thread 2 · reader
volatile read · while (!flag)
acquire: everything below this line cannot rise above it
The release keeps the write to x before the write to flag; the acquire keeps the read of x after the read of flag. Visibility runs forward along the edge: a thread that observes flag = true is guaranteed to observe x = 42 as well. Operations on the same side of a fence may still be reordered among themselves, and nothing here makes two accesses one step.
What volatile does not do
Every failure that needs indivisibility is still a failure. count++ remains LOAD, ADD, STORE, and the race lives in the gap: two threads load the same value, and one store overwrites the other. Volatile makes each of the three steps visible, which changes nothing about the gap between them.
The same shape appears wherever a decision and an action share state: check-then-act (if the flag is set, do the thing) and invariants that span fields (a size and the array it describes) are not protected by marking the fields volatile. The keyword orders accesses to one field; it does not make a sequence of them indivisible.
- Compound updates: count++, x = x + 1, and any other read-modify-write. Use AtomicInteger or a lock; the atomics lesson builds on this one.
- Check-then-act: two threads can both observe the same precondition and both act on it. The pair needs a lock, or an atomic method such as compareAndSet.
- Multi-field invariants: if two fields must agree, volatile on both still lets another thread read them between the two writes. One lock guards one invariant.
volatile is a visibility switch, not a lock. It changes when writes become visible and where they may move, never how many steps an operation has.
Double-checked locking, walked through
Double-checked locking is the one pattern where volatile is not optional, and it is worth replaying step by step because every step earns its place. The dangerous half is general unsafe publication, which the memory-model-problems lesson lays out; what makes this pattern worth its own replay is how specific the fix is.
- First read, outside the lock: if the field is already set, return it straight away. This fast path is the reason the field must be volatile. Without it, the reader can see a non-null reference whose construction is not yet visible.
- Take the lock: only this slow path locks, and only when the field looked null.
- Second check, inside the lock: while this thread waited, another thread may have finished constructing. The double check is what prevents a second instance.
- Construct: create the object. So far these are ordinary writes with no ordering promise.
- Assign the field: this is the volatile write, and as a release it keeps the constructor writes before it. Any thread that later reads the field and dereferences the object is guaranteed to see them.
- The local-variable idiom: classic listings read the field once into a local, test the local, then use it. That keeps the fast path to a single volatile read, and it is why the old code looks like two null checks.
The assignment that publishes an object needs the same fence as the object's fields. Drop volatile and the reference can become visible first; the reader then holds a non-null pointer to a half-built object. The final-field lesson covers the one case where a constructor earns that guarantee on its own.
Three jobs people hand to volatile
The keyword earns its place in three familiar shapes, and the lab below runs all three: a stop flag, a publication slot, and the counter people wish it fixed.
Chips choose the scenario and the mechanism, and the timeline steps through what each thread sees. Two scenarios end green once the right mechanism is chosen; the counter shows why volatile is the wrong mechanism for a read-modify-write.
One writer, many readers of a flag: volatile. Read-modify-write: atomic or lock. The lab keeps both rows of that sentence honest.
volatile lab · three jobs, one keyword
scenario
mechanism
stop flag
false
entering the loop
sleeping
The worker starts and enters while (!stop). main will flip the flag after a short nap. The flag is a plain field, so the write is an ordinary write with no promise attached.
outcome · stop flag
the worker may never exit: no visibility promise
A plain field allows the stale read, and the loop condition can even be hoisted. Nothing in the program promises the write is ever seen, and nothing throws when it is not.
long, double, and arrays
Volatile also changes what counts as one access for the 64-bit primitives. JLS 17.7 permits a non-volatile long or double write to be treated as two 32-bit writes, so a racing read can observe a torn value, half old bits and half new. Marking the field volatile makes its reads and writes single atomic accesses.
An array field is the opposite story. volatile int[] data makes the reference volatile: a thread is guaranteed to see a swap of the array itself. The elements are ordinary memory, so data[i]++ races like any other field, and volatile elements are not on offer. When element-level atomicity is what you need, AtomicIntegerArray or AtomicLongArray is the tool.
Volatile makes one access atomic, not a container. The spec offers it for long and double, and for a reference; it never reaches through a reference into elements or fields.
What it costs, qualitatively
On x86, the write side is the expensive half: a volatile store compiles to a store followed by a StoreLoad barrier, because store-load is the one reordering x86 otherwise allows. A volatile read compiles to an ordinary load, since x86 loads already behave as acquires. Architectures with weaker memory models pay on both sides in some form.
That asymmetry is a barrier shape, not a benchmark result. Treat volatile as neither free nor quotably expensive: it is a fence with a known direction, and the only honest number is one measured on the workload you actually have.
Treat volatile cost as a barrier shape, not a number. Know which side pays on your platform, then measure if it matters; the ordering guarantee is the feature, the barrier is the bill.
volatile or synchronized
The two tools overlap on visibility and differ on everything else. A getter that returns a volatile field needs no lock and never blocks; a synchronized getter excludes contenders and publishes the same way when the writer also synchronizes. The table is the quickest way to pick.
| Property | volatile | synchronized |
|---|---|---|
| Visibility of the last write | yes: a write happens-before every later read | yes: an unlock happens-before the next lock |
| Compound actions (count++, check-then-act) | no: the steps still race | yes: one thread inside the region at a time |
| Blocking | never: no thread ever waits | yes: contenders are parked until the monitor frees |
| Interruptible while waiting | not applicable: there is no wait | no: waiting for a monitor cannot be interrupted |
| Reentrancy | not applicable: no ownership | yes: the owning thread may re-enter |
| Typical use | flags, one-shot publication, double-checked locking, cached immutable snapshots | invariants, multi-field state, compound actions, anything a lock genuinely requires |
- A volatile read never coordinates with anyone, which is its whole advantage and the reason it is the default for a stop flag.
- A volatile write is cheap enough to build idioms on: one-shot publication and swapping a volatile reference to an immutable object are standard patterns.
- One agreement per field: if a field participates in an invariant guarded by a lock, guard it with that lock. Volatile adds a second, weaker agreement that sees individual fields, never the set.
volatile for the shape of latest value; synchronized for the shape of one at a time. When a field needs both, the lock is the answer; when it needs only visibility, the keyword pays a barrier instead of a wait.
volatile alone does not make check-then-act safe
The lazy singleton with a volatile field but no lock: two threads read the field, both see null, both construct, and the last assignment wins. Volatile made every write visible and the check-then-act still raced, because a volatile read and a volatile write do not stick together into one step. That is the line to remember in review: volatile publishes, it does not exclude. Double-checked locking is the version that adds the lock, and anything that needs both a look and an act needs the lock or an atomic method such as compareAndSet.
Interview angles
What exactly does volatile guarantee?+
Two things: visibility (a write to the field happens-before every subsequent read of it, so the reader sees the stored value) and ordering (a volatile write is a release, a volatile read an acquire, so accesses cannot be reordered across it in the forbidden direction). It guarantees nothing about compound actions.
The guarantee lives on the field access, not on the object or the surrounding code. Two threads reading and writing the same volatile field are participating in a happens-before edge; code that never touches the field gets no benefit from it.
Common misconception: That volatile makes access to the field thread-safe in the locking sense. It only removes the visibility and ordering failure; mutual exclusion is a different tool.
Follow-up: Where would a volatile read never block, and why is that the feature?
Does volatile make count++ thread-safe?+
No. count++ is LOAD, ADD, STORE, and volatile makes each of those steps visible without making them one step, so two threads can still load the same value and lose one store.
This is the most common review comment in the space: a class marked thread-safe by sprinkling volatile on fields while the operations on those fields remain compound. Use AtomicInteger (or a lock) for read-modify-write.
Common misconception: That visibility and atomicity are the same guarantee. Visibility says a write is seen; atomicity says a sequence cannot be interrupted.
Follow-up: Which class would you reach for, and when would LongAdder beat it?
Why must the double-checked locking field be volatile?+
Without it, the field assignment can become visible before the constructor writes do, so a second thread can pass the first null check, dereference a non-null reference, and read default field values. The volatile write is the release that keeps the constructor writes before the publication.
The fast path reads the field outside the lock, and an ordinary read of an unsynchronized write has no edge to attach to. Volatile supplies both halves: the release on the assignment and the acquire on the read.
if (instance == null) { // fast path: volatile read synchronized (Singleton.class) { if (instance == null) { // second check: no second instance instance = new Singleton(); // volatile write: release } } }
Follow-up: Which alternative singleton patterns sidestep the keyword entirely? The holder class, where class initialization supplies the edge, and the enum singleton.
Are volatile long and double reads and writes atomic, and what about a volatile array?+
Yes for the primitives: JLS 17.7 permits non-volatile long and double accesses to be treated as two 32-bit operations, and volatile removes that possibility. A volatile array field only makes the reference volatile; the elements are plain, so use AtomicIntegerArray for element atomicity.
Common misconception: That a volatile array protects its contents. It protects the slot holding the reference and nothing behind it.
Does volatile forbid all reordering?+
No. It forbids the two directions that matter: earlier actions cannot move below a volatile write, and later actions cannot move above a volatile read. Accesses on the same side of the fence can still be reordered among themselves, and there is no mutual exclusion anywhere.
The direction is what makes the pattern work. A writer stores data and then flips a volatile flag: the release keeps the data write first. A reader sees the flag and then reads the data: the acquire keeps the data read second.
Follow-up: Which fence does that pattern put on the expensive side on x86? The volatile write, which carries a StoreLoad barrier.
volatile or synchronized, in one line each?+
volatile: visibility and ordering for one field, never blocking. synchronized: visibility plus mutual exclusion, so compound actions and multi-field invariants are safe, at the cost of contenders waiting.
The choice is usually made by the shape of the state, not by cost: a flag is a single value that one thread writes, so volatile fits; a balance, a size next to an array, or a check-then-act needs the lock. Mixing the two on one field leaves the unlocked access outside the agreement.