Q44: What does the volatile keyword guarantee (Visibility vs Atomicity)?

volatile guarantees Memory Visibility and prevents Instruction Reordering.

  1. Reads and writes bypass CPU L1/L2 caches, writing directly to Main Memory.
  2. Establishes a Happens-Before Relationship.
  3. Does NOT guarantee Atomicity: Compound operations like count++ (read-modify-write) are NOT thread-safe under volatile alone.
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
  • volatile guarantees main memory visibility and prevents instruction reordering.
  • Does NOT guarantee atomicity for compound updates (i++). Use AtomicInteger.
Knowledge Check

Is the operation count++ thread-safe if count is declared as volatile int count?