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.


If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.

Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.