The volatile keyword in Java 5
We've so far seen that a volatile variable is
essentially one whose value is always held in main memory so that it can be accessed by different
threads. Java 5 adds a subtle change to this definition and adds some additional facilities
for manipulating volatile variables.
Java 5 definition of volatile
As of Java 5, accessing a volatile variable creates a memory barrier:
it effectively synchronizes all cached copies of
variables with main memory, just as entering or exiting a synchronized block that
synchronizes on a given object.
Generally, this doesn't have a big impact on the programmer, although it does occasionally make volatile
a good option for safe object publication. The infamous double-checked
locking antipattern actually becomes valid in Java 5 if the reference is declared volatile.
(See the page on how to fix double-checked locking for
And volatiles memory synchronization behaviour has occasionally allowed
more efficient design in some of the library classes via a technique dubbed
New Java 5 functionality for volatile variables
Perhaps more significant for most programmers is that as of Java 5, the VM exposes some
additional functionality for accessing volatile variables:
- truly atomic get-and-set operations are permitted;
- an efficient means of accessing the nth element of a volatile array
(and performing atomic get-and-set on the element) is provided.
These facilities are tucked away inside the sun.misc.Unsafe class1, but exposed
to the programmer in the form of various new concurrency classes:
On the following pages, we look at:
1. This is clearly a detail of Sun's implementation;
other JVMs could in principle implement the atomic classes without having a separate layer such as sun.misc.Unsafe.