The Visibility Problem: Why volatile Exists
You'll learn why threads sometimes can't see each other's changes to shared variables, even with correct logic.
The Invisible Update Problem
Imagine you're working with a partner in separate offices. You both have copies of the same document. When you make changes to your copy, your partner doesn't automatically see them—they're still looking at their old version. This is exactly what happens with threads and shared variables.
When multiple threads access a shared variable, each thread may work with its own cached copy stored in CPU registers or local CPU cache. Even if Thread A updates a variable in main memory, Thread B might keep reading from its stale cached copy. The update remains invisible to Thread B.
Why This Happens
Modern systems optimize performance through:
- CPU caching: Each processor core caches frequently-used values locally
- Compiler optimizations: The compiler may reorder operations or cache values in registers
- Memory buffers: Writes may be buffered before reaching main memory
These optimizations are fantastic for speed but create a problem: threads no longer have a consistent view of shared data.
A Classic Example
Thread A runs:
stopRequested = true; // Signal to stop
Thread B runs:
while (!stopRequested) { // May never see the update!
// Keep working...
}
Without proper synchronization, Thread B might never see the update to stopRequested. It keeps reading its cached false value forever, creating an infinite loop.
Enter volatile
The volatile keyword solves this by guaranteeing that:
- Every read comes directly from main memory (no stale cache)
- Every write goes directly to main memory (visible to all threads)
Key Takeaway: Without synchronization mechanisms like volatile or synchronized, threads may never see updates to shared variables due to CPU caching and compiler optimizations—a visibility problem that causes subtle, dangerous bugs.