Volatile Keyword and Array Thread Safety
Despite using the volatile keyword for the array reference, what potential issue remains in the code?
public class VolatileArray {
private volatile int[] data = {0, 0, 0, 0};
public void updateElement(int index, int value) {
data[index] = value;
}
public static void main(String[] args) {
VolatileArray va = new VolatileArray();
Runnable r = () -> {
for (int i = 0; i < va.data.length; i++) {
va.updateElement(i, i + 1);
}
};
Thread t1 = new Thread(r);
Thread t2 = new Thread(r);
t1.start();
t2.start();
}
}
A
The volatile keyword prevents the array from being modified by multiple threads completely.
B
The volatile keyword here ensures perfect thread safety for the updateElement method and its array elements.
C
Using volatile on an array makes all its elements immutable, eliminating any risk of mutation.
D
The volatile keyword does not provide atomicity or visibility guarantees for individual array elements, so race conditions can still occur.
Question Leaderboard
Not enough data yet to show leaderboard.
APFIVE