Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare array elements volatile in Java?

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?

like image 472
Joonas Pulakka Avatar asked Feb 10 '10 10:02

Joonas Pulakka


People also ask

Can we declare array as volatile in Java?

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.

How do you make an array volatile?

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.

How do you declare a volatile variable in Java?

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.

Can we make object volatile in Java?

No. To make them thread-safe, you have to synchronize the access to them.


2 Answers

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:

  • AtomicIntegerArray
  • AtomicLongArray
  • AtomicReferenceArray
  • java.util.concurrent.atomic Package Summary
like image 59
uthark Avatar answered Sep 20 '22 17:09

uthark


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

like image 45
Tim Jansen Avatar answered Sep 22 '22 17:09

Tim Jansen