Thread Safety with Static Arrays
Consider the StaticArray class provided below. What is the primary thread-safety issue demonstrated by this code?
public class StaticArray {
private static int[] values = new int[3];
public static void increaseAll() {
for (int i = 0; i < values.length; i++) {
values[i]++;
}
}
public static void main(String[] args) {
Thread t1 = new Thread(() -> StaticArray.increaseAll());
Thread t2 = new Thread(() -> StaticArray.increaseAll());
t1.start();
t2.start();
}
}
A
The static method increaseAll does not use any synchronization, leading to race conditions when multiple threads modify the static array concurrently.
B
Static arrays in Java are immutable by default, so no race condition exists.
C
The code is safe because both threads modify the same array in a static context without conflict.
D
The use of static prevents the need for instance-level synchronization, which automatically ensures thread safety.
Question Leaderboard
Not enough data yet to show leaderboard.
APFIVE