if we declare a variable volatile then the value of this variable will never be cached thread-locally and 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.
When is volatile enough?
If two threads are both reading and writing to a shared variable, then using
the volatile keyword for that is not enough. You need to use synchronization
in that case to guarantee that the reading and writing of the variable is
But in case one thread reads and writes the value of a volatile variable,
and other threads only read the variable, then the reading threads are
guaranteed to see the latest value written to the volatile variable. Without
making the variable volatile, this would not be guaranteed.
volatile enhancement in Java 5.0
Up to Java 4 volatile could be re-ordered by compiler with respect to any
previous read or write, leading to subtle concurrency bugs e.g. making it
impossible to implement a double check locking (very common idiom for a
This is fixed in Java 5.0 which extends the semantics for volatile which
cannot be reordered with respect to any following read or write anymore and
introduces a new memory model.
double checked locking with volatile
Important points on Volatile keyword in Java
1. The volatile keyword in Java is only application to a variable not class and method.
2. volatile keyword in Java guarantees that value of the volatile variable
will always be read from main memory and not from Thread's local cache.
3. Java volatile keyword doesn't mean atomic, its common misconception that
after declaring volatile ++ will be atomic, to make the operation atomic you
still need to ensure exclusive access using synchronized method or block in
4. In Java reads and writes are atomic.
5. write to a volatile variable in Java
establishes a happens-before relationship with subsequent reads of that same
6. Java volatile variable that is an object reference may be null.