Volatile Keyword and Array Thread Safety
In the provided code, the data array reference is declared with the volatile keyword. What potential concurrency issue still exists when multiple threads execute the updateElement method?
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
Using volatile on an array makes all its elements immutable, eliminating any risk of mutation.
B
The volatile keyword prevents the array from being modified by multiple threads completely.
C
The volatile keyword does not provide atomicity or visibility guarantees for individual array elements, so race conditions can still occur.
D
The volatile keyword here ensures perfect thread safety for the updateElement method and its array elements.
Question Leaderboard
Not enough data yet to show leaderboard.
