How do I make an array volatile? Because as I've come to understand, it's unsafe to make an array volatile?
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.
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.
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).
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.
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)
AtomicLongArray, AtomicIntegerArray, AtomicReferenceArray (java.util.concurrent.atomic).
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