What is volatile?
Solution and explanation
What it is
volatile is a field modifier that guarantees visibility and ordering: every read sees the most recent write by any thread, and writes are not reordered with surrounding operations in a way that breaks this. Without it, a thread may keep using a cached (stale) value.
Classic use: a stop flag
class Worker implements Runnable {
private volatile boolean running = true; // without volatile the loop may never stop
public void run() {
while (running) {
processNextMessage();
}
System.out.println("Worker stopped");
}
public void stop() { running = false; } // called from another thread
}
What volatile does NOT do
It does not make compound operations atomic:
private volatile int count = 0;
count++; // still a race: read, add, write
Use AtomicInteger or synchronized for that.
volatile vs synchronized vs atomic
- volatile: visibility only, no locking, very cheap. One writer / many readers of a simple flag or reference.
- synchronized: mutual exclusion + visibility for multi-step updates.
- AtomicInteger etc.: lock-free atomic updates of a single value + visibility.
Double-checked locking needs volatile
class ConfigHolder {
private static volatile Config instance;
static Config get() {
if (instance == null) {
synchronized (ConfigHolder.class) {
if (instance == null) instance = new Config(); // volatile prevents seeing a half-built object
}
}
return instance;
}
}
Note: the Java Memory Model's "happens-before" rule: a write to a volatile field happens-before every later read of that field.
