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 an example.) Andvolatiles memory synchronization behaviour has occasionally allowed more efficient design in some of the library classes via a technique dubbed synchronization 'piggybacking'.
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:
- the atomic wrapper classes AtomicInteger and AtomicLong provide atomic access to a single underlying volatile int or long;
- the AtomicIntegerArray, AtomicLongArray and AtomicReferenceArray classes provide efficient atomic access to the nth element of an underlying volatile array;
- the AtomicReferenceFieldUpdater class allows you to access an arbitrary volatile variable atomically.
Next...
On the following pages, we look at:
- the dangers of volatile variables: a common bug in which a seemingly atomic operation such as i++ actually isn't;
- When to use volatile?: a look at some typical cases.
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 assun.misc.Unsafe.
Article written by Neil Coffey (@BitterCoffey).
Reference: http://www.javamex.com/tutorials/synchronization_volatile_java_5.shtml