Concurrent Array Modification Race Condition
What is the primary issue when multiple threads execute incrementCounter concurrently?
public class CounterArray {
private int[] counters = new int[3];
public void incrementCounter(int index) {
counters[index] = counters[index] + 1;
}
public static void main(String[] args) {
CounterArray ca = new CounterArray();
Runnable task = () -> {
for (int i = 0; i < 1000; i++) {
ca.incrementCounter(1);
}
};
Thread t1 = new Thread(task);
Thread t2 = new Thread(task);
t1.start();
t2.start();
}
}
A
The counter update remains thread-safe because the threads increment the same index in a deterministic manner.
B
The array index is out of bounds because counters has only 3 elements.
C
The read-modify-write sequence in incrementCounter is not atomic, leading to race conditions on counters[1].
D
Since counters is an int array, the individual increments are atomic operations by default.
Question Leaderboard
| Rank | |||||
|---|---|---|---|---|---|
| #1 | busemagngr | 0 | 1 | 0m 00s | -10 |
| #2 | raufyildirim95 | 1 | 1 | 2m 30s | -50 |
| #3 | namansoin000 | 0 | 1 | 0m 56s | -66 |
Items per page:
10
1 – 3 of 3
APFIVE