Volatile
From site
- Essentially,
volatile
is used to indicate that a variable's value will be modified by different threads. - The value of this variable will never be cached thread-locally: all reads and writes will go straight to "main memory";
- Access to the variable acts as though it is enclosed in a synchronized block, synchronized on itself.
Differences between synchronized
and volatile
- A primitive variable may be declared volatile (whereas you can't synchronize on a primitive with synchronized);
- An access to a volatile variable never has the potential to block: we're only ever doing a simple read or write, so unlike a synchronized block we will never hold on to any lock;
- Because accessing a volatile variable never holds a lock, it is not suitable for cases where we want to read-update-write as an atomic operation (unless we're prepared to "miss an update");
- a volatile variable that is an object reference may be null (because you're effectively synchronizing on the reference, not the actual object).
Attempting to synchronize on a null object will throw a
NullPointerException
.