Before answering this question, let us see two important points about volatile variable.
- Using volatile variables reduces the risk of memory consistency errors, because any write to a volatile variable establishes a “happens-before” relationship with subsequent reads of that same variable. It means that changes to a volatile variable are always visible to other threads.
- Every read of a volatile variable will be read from the computer’s main memory, and not from the CPU cache. Similarly, every write to a volatile variable will be written to main memory, and not to the CPU cache.
Now, let us answer our original question, Can we make an array volatile in Java?
Yes, we can make an array volatile in Java but only the reference variable pointing to the array will be volatile not the elements of the array. Declaring an array volatile does not make its fields volatile. You’re declaring the reference itself volatile, not its elements.
protected volatile int[] arr = new int[10];
If you assign a new array to arr
variable, other threads will see the change but any change to individual elements of the array will not have volatile guarantee. If you change any element at any individual indices, “happens-before” guarantee will not be provided for such change.
If you want to provide this guarantee to the individual elements, volatile is not the right choice.
There are specific array for this type of requirement:
- AtomicIntegerArray: An int array in which elements may be updated atomically.
- AtomicLongArray: A long array in which elements may be updated atomically.
- AtomicReferenceArray: An array of object references in which elements may be updated atomically.
If you want to read about lock-free thread safe programming on single variables, you should check java.util.concurrent.atomic
package and classes of this package.