Java Concurrency With Static Arrays
What is the likely concurrency issue with the static grid in the above code and how might it be resolved?
public class StaticMatrix {
private static int[][] grid = new int[3][3];
public static void updateGrid(int value) {
for (int i = 0; i < grid.length; i++)
for (int j = 0; j < grid[i].length; j++)
grid[i][j] = value;
}
public static int readCell(int i, int j) {
return grid[i][j];
}
public static void main(String[] args) {
Thread t1 = new Thread(() -> StaticMatrix.updateGrid(5));
Thread t2 = new Thread(() -> {
System.out.println(StaticMatrix.readCell(1,1));
});
t1.start();
t2.start();
}
}
A
Array bounds exception because static grids require explicit locking during initialization.
B
Deadlock caused by static variables; marking grid as volatile would resolve it.
C
Memory leak due to the static grid; removing static would resolve it.
D
Race condition due to unsynchronized static access; adding synchronization around grid accesses would resolve it.
Question Leaderboard
Not enough data yet to show leaderboard.
APFIVE