NOTE
6.3 volatile
Java volatile visibility and ordering semantics, acquire/release-style happens-before behavior, atomic single reads/writes, and why volatile is not a lock.
This is a historical learning note and may contain outdated or incomplete understanding.
1. What volatile Is
volatile is a Java memory-ordering/visibility primitive for a variable. It is not a lightweight lock and does not provide mutual exclusion.
A write to a volatile variable happens-before a subsequent read of that same volatile variable.
This lets volatile act as a publication/visibility boundary for ordinary writes that occur before the volatile write.
2. What It Guarantees
Visibility
A thread performing a volatile read must observe a value consistent with the JMM’s volatile synchronization order rather than indefinitely reusing an unsynchronized stale value.
Ordering
The JMM restricts reordering across volatile accesses. JVMs implement those restrictions with compiler barriers and target-architecture instructions/fences as necessary.
Atomic Single Access
A single volatile read/write has the required atomic access semantics for that variable.
But:
volatile int count;
count++;
is still read → add → write, so concurrent increments can be lost.
3. Good Uses
- shutdown/state flags;
- safely publishing immutable or effectively immutable snapshots;
- state-machine variables where updates do not depend on the previous value;
- double-checked locking when the reference is correctly declared volatile.
4. When It Is Not Enough
Use a lock or atomic read-modify-write operation when an invariant spans multiple variables/steps.
5. Hardware Mapping
A historical x86 JIT build may show a locked instruction or fence around certain volatile operations, while ARM may emit different acquire/release instructions.
Do not define Java volatile as “write cache back to main memory and invalidate other caches.” The portable contract is the JMM happens-before/ordering semantics.