|
|
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
Volatile arrays in JavaA slight complication of Java volatile fields, and one sometimes overlooked, is that declaring an array volatile does not give volatile access to its fields!. At least, it doesn't when elements of the array are accessed with "normal" Java syntax. In other words:
So, what do we do if we want a truly volatile array in Java, where the array's individual fields have volatile semantics? Solution 1: use AtomicIntegerArray or AtomicLongArrayThe AtomicIntegerArray class implements an int array whose individual fields can be accessed with volatile semantics, via the class's get() and set() methods. Calling arr.set(x, y) from one thread will then guarantee that another thread calling arr.get(x) will read the value y (until another value is read to position x). Solution 2: re-write the array reference after each field writeThis is slightly kludgy and slightly inefficient (since what would be one write now involves two writes) but I believe it is theoretically correct. After setting an element of the array, we re-set the array reference to be itself: volatile int[] arr = new int[...]; ... arr[4] = 100; arr = arr; The marginal benefit of this technique could be:
Copyright © Javamex UK 2012. All rights reserved. |