Course contentsShow
← Computer Science
Lesson 2560 of 2,87257. Concurrency FundamentalsFree lesson

Volatile Variables

Understand volatile keyword semantics: ensuring visibility of changes across threads without full locks.

Volatile Variables

What you'll learn: How the volatile keyword guarantees that changes to a variable are immediately visible to all threads without requiring full locks.

The Visibility Problem

When multiple threads access shared variables, modern CPUs and compilers perform optimizations that can cause problems. A thread might cache a variable's value in a CPU register or local cache, never checking main memory for updates made by other threads. This means one thread's changes can be invisible to others—even though you're sharing the variable.

What Volatile Does

The volatile keyword tells the compiler and runtime: "This variable might change unexpectedly from other threads—don't optimize reads or writes to it." Every read of a volatile variable fetches the latest value from main memory, and every write immediately flushes to main memory, making it visible to all threads.

Analogy: Think of a shared whiteboard. Without volatile, each person keeps their own notepad copy and rarely checks the board. With volatile, everyone always reads from and writes directly to the board—no personal copies allowed.

What Volatile Doesn't Do

Volatile ensures visibility but not atomicity. Reading a volatile variable gives you the current value, but operations like counter++ (read-modify-write) still aren't thread-safe. For that, you need atomic operations or locks. Volatile is perfect for simple flags or status indicators where one thread writes and others read.

// Example use case (conceptual)
volatile boolean shutdownRequested = false;

// Thread 1 sets the flag
shutdownRequested = true;

// Thread 2 sees it immediately
while (!shutdownRequested) {
    // do work
}

Key Takeaway: Volatile variables guarantee visibility of changes across threads by preventing caching optimizations, but they don't make compound operations atomic—use them for simple flags, not complex updates.