Performance Characteristics of volatile
You'll learn why volatile is much faster than full synchronization, yet still comes with trade-offs.
The Core Idea
When you mark a variable as volatile, the JVM guarantees visibility across threads—but at a cost. Every read goes directly to main memory, and every write flushes immediately to main memory, bypassing CPU caches. This prevents certain compiler and processor optimizations like reordering, register caching, or batching multiple writes together.
However, volatile is significantly lighter than full synchronization (synchronized blocks or methods). Why? Because volatile doesn't involve locking—no threads wait, no monitor acquisition, no context switching overhead. It's essentially a memory fence instruction, not a mutual exclusion mechanism.
The Trade-Off
What volatile prevents:
- The compiler can't cache the value in a CPU register across reads
- The processor can't reorder reads/writes around volatile accesses
- Loop optimizations that would "hoist" a volatile read out of a loop are forbidden
What it costs:
- Slightly slower reads/writes than normal variables (memory barrier overhead)
- Less optimization flexibility for the JIT compiler
What it saves vs synchronized:
- No thread blocking or waiting
- No monitor contention
- No context switching penalty
- Much lower latency for uncontended access
The Practical Impact
For a simple status flag read in a tight loop, volatile adds minimal overhead—maybe a few nanoseconds per access. Meanwhile, synchronized could add hundreds of nanoseconds or more due to locking mechanics, even when uncontended.
Key Takeaway:
volatile sacrifices some CPU optimizations for memory visibility but remains far cheaper than synchronization—use it for simple flags and state variables where atomicity isn't required, but visibility is critical.