Volatile Arrays in Java
A slight complication of Java volatile fields, and one sometimes overlooked, was that declaring an array Volat Ile does not give volatile access to its fields!. At least, it doesn ' t when elements of the array is accessed with "normal" Java syntax. In other words:
- It is unsafe for call arr[x] = y on a array (even if declared volatile) in one thread and then expect ARR[X] to return y from another thread;
- On the other hand, it 's safe to call arr = new int[] (or whatever) and expect another thread to then re Ad the new array as that referenced by arr: This is the meant by declaring the array reference volatile .
So, what does we do if we want a truly volatile array in Java, where the array's individual fields has the volatile semantics?
Solution 1:useAtomicintegerarrayOrAtomiclongarray
The Atomicintegerarray class implements an int array whose individual fields can is accessed with VO Latile semantics, via the class's get () and set () methods. Calling Arr.set (x, y) from one thread would then guarantee that another thread calling arr.get (x) would re Ad the value y (until another value is read to position x).
Solution 2:re-write the arrayReferenceAfter each field write
This was slightly kludgy and slightly inefficient (since what would being one write now involves II writes) but I believe it is theoretically correct. After setting a element of the array, we re-set the array reference to be itself:
Volatile int[] arr = new int[...]; ... arr[4] = 100;arr = arr;
The marginal benefit of this technique could is:
- It may allow you to fix some broken code with minimal changes if you have code already (incorrectly) using a volatile< /c1> array and expecting thread-safe element access;
- It saves us creating the wrapper object around the array (which is what happens with Integerarray and Longarr Ay);
- It's more, or less, the only option for an array types with no available atomic wrapper (e.g. a float array).
Volatile Arrays in Java