Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java volatile array?

Tags:

How do I make an array volatile? Because as I've come to understand, it's unsafe to make an array volatile?

like image 201
Michael Avatar asked Mar 02 '11 21:03

Michael


People also ask

What is volatile array in Java?

The volatile is a modifier in Java which only applies to member variables, both instance and class variables, and both primitive and reference types. It provides the happens-before guarantee which ensures that a write to a volatile variable will happen before any reading.

Can array be declared volatile in Java?

The elements of an array don't have the volatile behavior though we declare it volatile. To resolve this, Java provides two classes namely AtomicIntegerArray and, AtomicLongArray, these represents arrays with atomic wrappers on (respective) variables, elements of these arrays are updated automatically.

Is volatile deprecated in Java?

There are some uses of volatile that are NOT deprecated, because they are useful (e.g. in code that directly loads or stores from specified memory locations, such as in device drivers).

What is volatile in Java with example?

Volatile keyword is used to modify the value of a variable by different threads. It is also used to make classes thread safe. It means that multiple threads can use a method and instance of the classes at the same time without any problem. The volatile keyword can be used either with primitive type or objects.


2 Answers

Declaring an array volatile does not give volatile access to its fields. You're declaring the reference itself volatile, not its elements.
In other words, you're declaring a volatile set of elements, not a set of volatile elements.

The solution here is to use AtomicIntegerArray in case you want to use integers. Another way (but kinda ugly) is to rewrite the reference to the array every time you edit a field.

You do that by:

arr = arr;  

(as I said... ugly)

like image 104
nicolaas Avatar answered Sep 28 '22 19:09

nicolaas


AtomicLongArray, AtomicIntegerArray, AtomicReferenceArray (java.util.concurrent.atomic).

like image 37
jtahlborn Avatar answered Sep 28 '22 18:09

jtahlborn