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?
Use
AtomicIntegerArrayorAtomicLongArrayorAtomicReferenceArrayThe
AtomicIntegerArrayclass implements an int array whose individual fields can be accessed with volatile semantics, via the class’sget()andset()methods. Callingarr.set(x, y)from one thread will then guarantee that another thread callingarr.get(x)will read the value y (until another value is read to position x).See: