Q44: What does the volatile keyword guarantee (Visibility vs Atomicity)?
volatile guarantees Memory Visibility and prevents Instruction Reordering.
- Reads and writes bypass CPU L1/L2 caches, writing directly to Main Memory.
- Establishes a Happens-Before Relationship.
- Does NOT guarantee Atomicity: Compound operations like
count++(read-modify-write) are NOT thread-safe undervolatilealone.
Volatile Visibility Flag
public class FlagWorker implements Runnable {
private volatile boolean running = true; // Visibility guaranteed across threads
public void stop() { running = false; }
@Override
public void run() {
while (running) { /* work */ }
}
}💡 Volatile ensures modifications to running are visible immediately across worker threads.
Key Takeaways
volatileguarantees main memory visibility and prevents instruction reordering.- Does NOT guarantee atomicity for compound updates (
i++). UseAtomicInteger.
Knowledge Check
Is the operation count++ thread-safe if count is declared as volatile int count?