Common Use Cases: Status Flags and Control Variables
What you'll learn: When volatile alone is enough to safely coordinate threads—without needing heavier synchronization.
Why volatile Works for Simple Flags
Some multi-threaded scenarios don't need atomic compound operations—they just need one thread to signal a simple state change that other threads can immediately see. volatile excels here because it guarantees visibility without the overhead of locks.
The most common pattern: a boolean flag that controls thread behavior. One thread writes the flag; others read it to decide whether to continue running, change modes, or respond to an event.
Typical Scenarios
Thread Stop Flags:
private volatile boolean stopRequested = false;
public void run() {
while (!stopRequested) {
// do work
}
}
public void shutdown() {
stopRequested = true; // Writer thread
}
Because stopRequested is volatile, the write in shutdown() is immediately visible to the reader in run(). No synchronization needed—the flag is only written once per state change, and reading/writing a boolean is already atomic.
Status Indicators:
private volatile boolean ready = false;
private String data;
public void prepareData() {
data = loadExpensiveData();
ready = true; // Signal completion
}
public void useDataIfReady() {
if (ready) { // Safely read flag
process(data);
}
}
The volatile ready flag ensures the write to data (which happens before setting ready) is visible to any thread that sees ready == true.
When This Pattern Works
Use volatile flags when:
- Only one writer updates the variable (or writes are independent)
- Reads and writes are simple assignments (no increment, toggle, or check-then-act)
- You need lightweight signaling, not complex coordination
Key Takeaway: Volatile is ideal for simple boolean flags and status variables where visibility matters but atomicity of compound operations doesn't—like stop signals, readiness indicators, or mode switches.