volatile Keyword
Use volatile for visibility/order guarantees, not for atomic increments.
📌 Key Idea
volatile ensures reads see the latest write and creates a happens-before edge between writer and reader. It does not make compound operations like count++ atomic.Problem it solves
- Threads may keep stale cached values and never observe state changes from other threads.
- Flags like shutdown/config-refresh can fail unpredictably without visibility guarantees.
volatileensures latest-write visibility and ordering for simple shared variables.
Why It Matters
- Fixes stale-read bugs in stop flags and state publication.
- Common interview trap: confusing visibility with atomicity.
Visual
🧭 Visibility with `volatile`
Thread A: flag = true (volatile write)
|
| happens-before
v
Thread B: if (flag) { ... } (volatile read sees latest)⚠️ What it does NOT do
volatile int count = 0; count++; // read + add + write (not atomic) Need AtomicInteger or lock for compound updates.
When to Use
- One writer / many readers for a status flag (shutdown, config refresh).
- Safe publication of immutable snapshot references.
When NOT to Use
- Counters and compound state transitions (
x++, check-then-act). - Invariants requiring multiple fields to change together.
Code Variations
1️⃣ Correct use: stop flagjava
class Worker implements Runnable {
private volatile boolean running = true;
void stop() { running = false; }
@Override
public void run() {
while (running) {
doWork();
}
}
}Without
volatile, worker thread may never see updated flag.2️⃣ Wrong use: volatile counterjava
class Metrics {
private volatile int count = 0;
void inc() { count++; } // not atomic
}Use
AtomicInteger.incrementAndGet() or lock-protected section.volatile vs synchronized vs atomic classes
| Aspect | `volatile` | `synchronized` / `Lock` | `Atomic*` classes |
|---|---|---|---|
| Visibility | ✅ | ✅ | ✅ |
| Atomic compound updates | ❌ | ✅ | ✅ (single variable ops) |
| Blocking | Non-blocking | May block on lock | Non-blocking (CAS-based) |
| Best fit | Flags / publication | Critical sections with invariants | Counters and atomic state ops |
Interview Q&A
Quick Cheat Sheet
GuaranteeVisibility + ordering (happens-before).
No guaranteeAtomicity of read-modify-write.
Use forFlags, publication of immutable references.