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

Dangers of the volatile keyword

On this page, I want to look at a couple of common bugs that programmers introduce when they use volatile.

Volatile arrays don't give volatile access to elements

If you declare arr[] is volatile, that means that the reference to the array is volatile; but individual field accesses (e.g. arr[5]) are not thread-safe. See the section on volatile arrays in Java for a couple of workarounds.

Unary operations (++, --) aren't atomic

A danger of "raw" volatile variables is that they can misleadingly make a non-atomic operation look atomic. For example:

volatile int i;
i += 5;

Although it may look it, the operation i += 5 is not atomic. It is more the equivalent to:

// Note that we can't literally synchronize on an int primitive!
int temp;
synchronized (i) {
  temp = i;
temp += 5;
synchronized (i) {
  i = temp;

So another thread could sneak in the middle of the overall operation of i += 5.

How to fix this bug

To fix this bug and provide a "true" atomic get-set operation, use one of the atomic wrapper classes such as AtomicInteger. Prior to Java 5, pretty much the only solution is to introduce an explicit lock object and synchronize on it around all accesses to the variable.

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 2014. All rights reserved.