Home  Synchronization and concurrency  wait/notify  final  volatile  synchronized keyword  Java threading  Deadlock (and avoiding it)  Java 5: ConcurrentHashMap  Atomic variables  Explicit locks  Queues  Semaphores  CountDownLatch  CyclicBarrier

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 an example.) And volatiles 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:


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.

Article written by Neil Coffey (@BitterCoffey).


 LetterMeister (word puzzle game for iPhone)
 Currency Quoter (currency converter/predictor)
 French Vocab Games for iPhone/iPad
 Vocabularium: create Spanish vocab podcasts

Java programming articles and tutorials on this site are written by Neil Coffey (@BitterCoffey). Suggestions are always welcome if you wish to suggest topics for Java tutorials or programming articles, or if you simply have a programming question that you would like to see answered on this site. Most topics will be considered. But in particular, the site aims to provide tutorials and information on topics that aren't well covered elsewhere, or on Java performance information that is poorly described or understood. Suggestions may be made via the Javamex blog (see the site's front page for details).
Copyright © Neil Coffey 2015. All rights reserved.