Can we make Array volatile using volatile keyword in Java?

Java 8Object Oriented ProgrammingProgramming

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;
raja
Published on 05-Aug-2019 14:49:42
Advertisements