|
|
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 keywordOn 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 elementsIf 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 atomicA 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
// 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 bugTo 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. Copyright © Javamex UK 2012. All rights reserved. |