Video in progress
What is a volatile variable for?
volatile guarantees that a write is immediately visible to other threads, and it forbids the compiler from reordering around that variable. But it does not make operations atomic.
📖 Answer
The classic case is a stop flag:
class Worker implements Runnable {
private volatile boolean running = true;
public void run() {
while (running) {
processNext();
}
}
public void stop() { running = false; }
}
Without volatile, the JIT may read running once and not re-read it inside the loop. As a result, the thread keeps spinning forever even after stop() is called. This isn't theory: it shows up often even in a simple test.
When it is enough:
- one thread writes and the others only read;
- the new value doesn't depend on the old one (
flag = true,config = newConfig).
When it is not enough: read-then-write operations like count++ or if (x == null) x = .... There you need synchronized or Atomic*.
Sign up to mark studied questions and save your progress.