English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The volatile modifier indicates to the JVM that threads accessing volatile variables should always obtain data from memory. That is, threads should not cache volatile variables.
Accessing a volatile variable will synchronize all copies of variables cached in the main storage. Mutable variables can only be applied to object types or private instance variables. A volatile object reference can be null.
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 } }
Although we declare the array as volatile, the elements of the array do not have volatile behavior.
To solve this problem, Java provides two classes, AtomicIntegerArray and AtomicLongArray, which represent arrays with atomic wrapping on their variables, and the elements of these arrays are automatically updated.
That is, the individual elements of the arrays represented by these classes can be accessed as volatile variables. These classes provideget()
andset()
variables to retrieve or assign values to each element separately.
Since atomic wrappers are available for integer and long types, and the rest of the data types are available, the reference value of the array must be reassigned each time an element is assigned to the array.
volatile int[] myArray = new int[3]; myArray [0] = 100; myArray = myArray; myArray [1] = 50; myArray = myArray; myArray [2] = 150; myArray = myArray;