views:

243

answers:

2

Is there a way to declare array elements volatile in Java? I.e.

volatile int[] a = new int[10];

declares the array reference volatile, but the array elements (e.g. a[1]) are still not volatile. So I'm looking for something like

volatile int[] a = new volatile int[10];

but it doesn't work that way. Is it possible at all?

+7  A: 

use AtomicIntegerArray or AtomicLongArray

The 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).

http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/atomic/AtomicIntegerArray.html http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/atomic/AtomicLongArray.html http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/atomic/package-summary.html

uthark
I wonder why there are specific `AtomicArrays` for int and long, but not for other primitive types... But of course the rest of the primitives could be faked by using their wrappers in an `AtomicReferenceArray`.
Joonas Pulakka
I think AtomicIntegerArray and AtomicLongArray are optimized to work with integer and long respectively.
uthark
+4  A: 

No, you can't make array elements volatile. See also http://jeremymanson.blogspot.com/2009/06/volatile-arrays-in-java.html .

Tim Jansen
Actually you can, but with additional efforts.
uthark
Thanks for that great link!
Joonas Pulakka