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?
Yes, you can make the array volatile but that will only cover change to the reference variable pointing to an array, it will not cover changes in individual array elements.
You can only make variable pointing to array volatile. If array is changed by replacing individual elements then guarantee provided by volatile variable will not be held.
The volatile modifier is used to let the JVM know that a thread accessing the variable must always merge its own private copy of the variable with the master copy in the memory. Accessing a volatile variable synchronizes all the cached copied of the variables in the main memory.
No. To make them thread-safe, you have to synchronize the access to them.
Use AtomicIntegerArray
or AtomicLongArray
or AtomicReferenceArray
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).
See:
No, you can't make array elements volatile. See also http://jeremymanson.blogspot.com/2009/06/volatile-arrays-in-java.html .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With