library
advancedThe volatile Keyword
Use volatile for visibility guarantees between threads and understand its limitations compared to synchronization.
volatile is a field modifier that guarantees visibility and ordering of reads and writes across threads.
Non-volatile field = writing on your personal notepad (private cache). Other people can't see it until you post it on the shared whiteboard. volatile = writing directly on the shared whiteboard (main memory). Everyone sees the update immediately.
Key Concepts
1
Without volatile:
- Thread A writes to a field → Thread B may never see the update (CPU cache, compiler optimization)
- The JVM is allowed to cache field values in CPU registers and reorder instructions
2
With volatile:
- Every write to a volatile field is immediately flushed to main memory
- Every read of a volatile field reads from main memory (not cache)
- Prevents instruction reordering around volatile accesses (happens-before guarantee)
3
What volatile does:
- Visibility: changes by one thread are visible to all threads
- Ordering: reads/writes before a volatile write happen-before reads after a volatile read
4
What volatile does NOT do:
- Atomicity of compound operations: count++ is NOT atomic even if count is volatile (read-modify-write)
- Mutual exclusion: volatile doesn't lock — multiple threads can read and write simultaneously
5
Use cases:
- Flags: volatile boolean running = true; (checked by one thread, set by another)
- Double-checked locking: the singleton field MUST be volatile
- Publishing immutable objects: volatile reference to an immutable object
6
For atomic compound operations (increment, compare-and-set), use AtomicInteger, AtomicReference, or synchronized.