What Java's volatile Does and Does Not Guarantee
Data Structure DesignModel answerLast updated
Explain the Java Memory Model guarantees of volatile fields: visibility, happens-before ordering and reordering limits, its gaps such as compound atomicity, and when to prefer locks or atomics.
You are reviewing a concurrent Java codebase and need to explain to a teammate exactly what marking a field volatile buys them.
Write an answer that covers:
- Visibility. What happens when one thread writes a volatile field and another reads it?
- Ordering. How does
volatilecreate a happens-before relationship, and what does this imply for other, non-volatile data written beforehand? - Reordering. Which reorderings by the compiler, JIT or CPU are forbidden around volatile reads and writes, and which are still allowed?
- Limits. What does
volatilenot provide? Use at least one concrete broken example, such as a counter incremented from several threads. - Comparison. How does it differ from
synchronized/ReentrantLockand from atomic classes such asAtomicInteger? - Use cases. Give a few situations where
volatileis the right tool and a few where it is not.
Short code snippets are welcome. Be precise about what is guaranteed versus what merely tends to happen on typical hardware.
Hints
Hint 1
Think in terms of the Java Memory Model's happens-before relation rather than 'flushing to main memory'. What does a volatile write establish with respect to a later volatile read that observes it?
Hint 2
Describe a volatile write as a release and a volatile read as an acquire. Which operations may not cross each of them, and which ordinary operations may still move into the protected region?
Hint 3
Take `count++` on a volatile int and trace it as read, add, write across two threads. Then ask which tools (atomics, locks) fix that problem and which scenarios, like a single-writer stop flag, do not need them.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Short answer
volatile gives visibility and ordering for a single variable, plus atomic reads and writes of that variable (including long and double). It does not give mutual exclusion, so compound actions like count++ or check-then-act are still racy.
1. Visibility
Without volatile, the JMM allows a thread to keep a field in a register or cache and never observe another thread's write. A volatile read always sees the latest write in the synchronization order of volatile accesses. Think of it as a formal rule rather than as "flushing to main memory".
Classic failure:
class Worker implements Runnable {
private boolean running = true; // not volatile: bug
public void run() { while (running) work(); }
public void stop() { running = false; }
}
No happens-before edge links stop() to the loop, so the JIT may hoist the read and spin forever. Declaring running as volatile prevents that.
2. Ordering and happens-before
A write to a volatile variable happens-before every later read of that variable that observes the write. Because happens-before is transitive and includes program order, everything the writer did before the volatile write is visible to the reader after the volatile read.
int timeoutMs; String endpoint; // plain fields
volatile boolean ready;
// Thread A
timeoutMs = 5000; endpoint = "svc"; ready = true;
// Thread B
if (ready) connect(endpoint, timeoutMs); // sees 5000 and "svc"
This is safe publication: the plain fields piggyback on the volatile pair. Many java.util.concurrent classes rely on exactly this pattern.
3. Reordering rules
- Volatile write = release. Earlier reads and writes cannot be moved after it.
- Volatile read = acquire. Later reads and writes cannot be moved before it.
- Volatile accesses are not reordered with each other, including write followed by read (the StoreLoad case). This is what makes them sequentially consistent among themselves, and it is the costly fence.
- Ordinary accesses may still move into the region: code after a volatile write can float above it, and code before a volatile read can sink below it.
Cost: on x86 a volatile read is a plain load and a volatile write needs a StoreLoad fence (e.g. lock add). On ARMv8 the JIT uses ldar/stlr. Reads are cheap, writes are more expensive, but neither blocks.
4. What volatile does not guarantee
- Compound atomicity.
count++is read, add, write. Two threads can both read 5 and both write 6, losing an update.
private volatile int count;
void inc() { count++; } // broken
private final AtomicInteger safe = new AtomicInteger();
void incSafe() { safe.incrementAndGet(); } // correct
- Check-then-act and multi-field invariants.
if (balance >= amt) balance -= amt;is a race even ifbalanceis volatile. An invariant likelow <= highover two volatile fields cannot be preserved. - Visibility of later mutation through the reference.
volatile Foo refmakes the reference volatile. Writes toref.xafter publication are plain writes. - Array elements.
volatile int[] amakes the array reference volatile, nota[i]. UseAtomicIntegerArrayorVarHandle. - Latency bounds. The JMM promises ordering and eventual visibility, not a specific time.
5. Comparison
volatile | synchronized / ReentrantLock | Atomic* / VarHandle | |
|---|---|---|---|
| Visibility | Yes | Yes (unlock happens-before next lock) | Yes |
| Mutual exclusion | No | Yes | No |
| Compound atomicity | No | Yes | Single-variable read-modify-write via CAS |
| Blocking | Never | Can block and park | Never (lock-free, may retry) |
| Cost | Cheap reads, fenced writes | Higher, grows with contention | About volatile plus CAS retries |
Entering a monitor behaves like a volatile read and exiting behaves like a volatile write, so locks give the same visibility guarantees plus exclusion. ReentrantLock also adds tryLock, timeouts, interruptibility, fairness and multiple conditions. Atomics are essentially volatile plus compare-and-swap.
Rule of thumb: use volatile for a single writer or for writes that do not depend on the current value, with no cross-variable invariant. Use atomics for single-variable read-modify-write. Use locks for anything larger.
6. Good use cases
- Stop or status flags such as the
runningexample. - Single-writer metrics, for example a
volatile long lastHeartbeatwritten by one thread and read by many. Volatile also prevents 64-bit tearing. - Immutable snapshot publication: build a new immutable object, then swap the reference.
private volatile Map<String, Rate> rates = Map.of();
void refresh(Map<String, Rate> fresh) { rates = Map.copyOf(fresh); }
Rate get(String c) { return rates.get(c); } // lock-free readers
- Double-checked locking. It is correct only if the field is volatile; otherwise another thread can see a non-null reference to a partially constructed object.
private static volatile Registry instance;
static Registry get() {
Registry r = instance;
if (r == null) {
synchronized (Registry.class) {
r = instance;
if (r == null) instance = r = new Registry();
}
}
return r;
}
Poor use cases
Counters, running totals, "check balance then withdraw", or any invariant touching multiple fields. These need atomics or locks.
Common mistakes
- Saying volatile "makes operations atomic" or "makes the variable thread-safe".
- Explaining it as "reads go to main memory" instead of using happens-before.
- Forgetting that the guarantee covers earlier plain writes only if the reader actually observes the volatile write.
- Assuming a volatile collection reference makes the collection's contents thread-safe.
- Using volatile for a
volatilecounter because it "looks" synchronized.
Validating your understanding
Write a stress test with two threads incrementing a volatile int one million times each. The result will usually fall short of two million. Replacing it with AtomicInteger or a lock fixes it. Removing volatile from the stop flag, run under a JIT-compiled loop, can demonstrate the hang.