Can we make Array volatile using volatile keyword in Java?


The volatile modifier indicates the JVM that the thread accessing a volatile variable should get data always from the memory. i.e. a thread should not cache the volatile variable.

Accessing a volatile variable synchronizes all the cached copied of the variables in the main memory. Volatile can only be applied to instance variables, which are of type object or private. A volatile object reference can be null.

Example

public class MyRunnable implements Runnable {
   private volatile boolean active;
   public void run() {
      active = true;
      while (active) { // line 1
         // some code here
      }
   }
   public void stop() {
      active = false; // line 2
   }
}

Making an array volatile

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.

i.e. can access individual elements of these arrays represented by these classes as volatile variables. These classes provides get() and set() variables to retrieve or, assign values to each elements individually.

Since atomic wrappers are available for integer and long types for remaining datatypes you need to reassign the reference value of the array each time you assign an element to it.

volatile int[] myArray = new int[3];
myArray [0] = 100;
myArray = myArray;
myArray [1] = 50;
myArray = myArray;
myArray [2] = 150;
myArray = myArray;

Updated on: 02-Jul-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements