volatile and what it does not fix
30 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)One thread sets a stop flag to true, but the worker thread keeps running as if nothing changed. The change was made, yet the other thread never saw it. Why, and what is the smallest fix?
volatile: reads and writes go to main memory
volatile makes every read of a field see the latest write from any thread, but it does not make compound steps like count++ atomic.
A volatile field is one that the JIT and the CPU may not keep in a private copy. In the simple picture from the last lesson, every read of a volatile field goes to main memory and every write goes straight back to it.
class Booking { volatile boolean open; // every thread sees the latest value volatile String status; // works for references too volatile long lastUpdated; // reads and writes of long are also atomic}The Java rule is stronger than "no caching". After a thread reads a volatile field and sees a value, it also sees every other write the writer made before that volatile write. The lesson "Happens-before in plain words" builds on this.
Real CPUs do this with special instructions, but the picture gives the right answer.
long and double writes may be split into two 32-bit halves on some JVMs. Declaring them volatile makes each single read and write one step.Fixing the stop flag with volatile
Fixing a stop flag needs one word: declare the flag volatile. The worker's loop must now read the field on every pass, so it sees true soon after main writes it.
Example 1 · The stop flag, fixed with volatile
public class VolatileStopDemo { static volatile boolean stop = false; // the only change: volatile
public static void main(String[] args) throws InterruptedException { Thread worker = new Thread(() -> { long rounds = 0; while (!stop) { rounds++; } System.out.println("worker: saw stop, ending"); }, "worker-1"); worker.start();
Thread.sleep(100); System.out.println("main: setting stop = true"); stop = true;
worker.join(); // no timeout needed now System.out.println("main: worker still running? " + worker.isAlive()); }}main: setting stop = true worker: saw stop, ending main: worker still running? false
What this code does
- This is the program that hung in the last lesson, with
volatileadded tostop. The worker now always sees the change, sojoin()needs no timeout and no daemon thread. - Main prints before it writes
stop, and the worker prints only after it sees it, so the three lines always come in this order.
Example 2 · Many Tatkal agents wait on one volatile flag
class TatkalWindow { private volatile boolean open = false;
void openNow() { open = true; }
boolean isOpen() { return open; }}
public class TatkalAgentsDemo { public static void main(String[] args) throws InterruptedException { TatkalWindow window = new TatkalWindow(); String[] result = new String[3]; Thread[] agents = new Thread[3];
for (int i = 0; i < 3; i++) { int me = i; agents[i] = new Thread(() -> { while (!window.isOpen()) { // wait for 10:00 AM } result[me] = Thread.currentThread().getName() + " saw the window open"; }, "agent-" + (i + 1)); agents[i].start(); }
Thread.sleep(50); System.out.println("10:00 AM: Tatkal window opens"); window.openNow();
for (Thread a : agents) { a.join(); } for (String r : result) { System.out.println(r); } }}10:00 AM: Tatkal window opens agent-1 saw the window open agent-2 saw the window open agent-3 saw the window open
What this code does
- One writer (
openNow) and three readers. Every agent sees the window open, because each pass of its loop reads the volatileopenagain. - Each agent stores its message in its own array slot, and main prints the slots after
join(), so the output order is fixed even though the agents finish in any order.
This works on every JVM and every CPU, because the Java rules promise it. No sleep, print or lock is needed, and reading a volatile field is cheap compared with taking a lock.
volatile count++ is still a race
volatile does not make count++ atomic. Each read and each write is visible, but count++ is still three steps: read, add 1, write. Two threads can both read 500, both write 501, and one visit is lost.
Example 3 · Mistake: a volatile counter still loses visits
class VisitorCounter { volatile int count = 0; // visible, but still not atomic
void visit() { count++; // read, add 1, write back }}
public class VolatileCounterRaceDemo { public static void main(String[] args) throws InterruptedException { VisitorCounter counter = new VisitorCounter(); Runnable task = () -> { for (int i = 0; i < 100_000; i++) { counter.visit(); } }; Thread[] gates = new Thread[4]; for (int i = 0; i < 4; i++) { gates[i] = new Thread(task, "gate-" + (i + 1)); gates[i].start(); } for (Thread g : gates) { g.join(); }
System.out.println("Expected: 400000"); System.out.println("Actual: " + counter.count); }}Expected: 400000 Actual: 351557
What this code does
- The field is
volatile, yet the total is usually short, and the number changes from run to run (once in a while a run comes out right). Two gates can still read the same value and both write value + 1. volatilemade every read and write visible. It did nothing to keep the three steps ofcount++together.
Example 4 · The fix: a synchronized counter
class VisitorCounter { private int count = 0; // no volatile needed: the lock gives visibility
synchronized void visit() { count++; }
synchronized int get() { return count; }}
public class CounterFixDemo { public static void main(String[] args) throws InterruptedException { VisitorCounter counter = new VisitorCounter(); Runnable task = () -> { for (int i = 0; i < 100_000; i++) { counter.visit(); } }; Thread[] gates = new Thread[4]; for (int i = 0; i < 4; i++) { gates[i] = new Thread(task, "gate-" + (i + 1)); gates[i].start(); } for (Thread g : gates) { g.join(); }
System.out.println("Expected: 400000"); System.out.println("Actual: " + counter.get()); }}Expected: 400000 Actual: 400000
What this code does
synchronized visit()lets only one gate runcount++at a time, so no visit is lost. The result is 400000 on every run.- The field is no longer
volatile: the lock already gives visibility to every thread that reads throughsynchronized get().
The same goes for check-then-act: if (seats > 0) seats--; on a volatile seats can still sell the last seat twice. Whenever a new value depends on the old one, you need a lock (or an atomic class such as AtomicInteger, covered in the Locks & Atomic Variables module).
When volatile is the right tool
volatile is the right tool when a thread writes a field without first reading it, and other threads only need to see the latest value. Stop flags, "is ready" flags and status fields fit this exactly.
Example 5 · A volatile status field for exam results
class ResultServer { private volatile String phase = "UPLOADING"; // one writer, many readers
void setPhase(String p) { phase = p; // a plain write: no read-modify-write }
String phase() { return phase; }}
public class ResultStatusDemo { public static void main(String[] args) throws InterruptedException { ResultServer server = new ResultServer();
Thread admin = new Thread(() -> { try { Thread.sleep(20); server.setPhase("CHECKING"); Thread.sleep(20); server.setPhase("PUBLISHED"); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }, "admin");
Thread portal = new Thread(() -> { while (!server.phase().equals("PUBLISHED")) { Thread.onSpinWait(); // a hint: "I am busy-waiting" } System.out.println("portal: results are live"); }, "portal");
portal.start(); admin.start(); admin.join(); portal.join(); System.out.println("main: final phase is " + server.phase()); }}portal: results are live main: final phase is PUBLISHED
What this code does
- Only the admin thread writes
phase, and each write replaces the old value without reading it. That is exactly the casevolatilehandles alone, with no lock. Thread.onSpinWait()(Java 9) tells the CPU the thread is busy-waiting, so it can save power. It does not affect correctness; thevolatileread does.
- Good: a stop or shutdown flag set by one thread and read by many.
- Good: a status or "latest value" field (
phase,percent,latestPrice) where each write replaces the old value. - Not enough: counters, totals, balances or
if (x > 0) x--(new value depends on old): use a lock. - Not enough: two fields that must change together (min and max, seat and buyer): use a lock or one object holding both.
Find the bug
Find the volatile mistake
Click the line that is wrong in each snippet.
The worker must see the stop request.
Round 1 of 4x = something that uses x, volatile alone is not enough.Next step
Check your understanding
11 quick questions