Concurrent Array Modification Race Condition
Consider the following CounterArray class. What is the primary issue that arises when multiple threads concurrently execute the incrementCounter method?
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 read-modify-write sequence in incrementCounter is not atomic, leading to race conditions on counters[1].
B
The array index is out of bounds because counters has only 3 elements.
C
Since counters is an int array, the individual increments are atomic operations by default.
D
The counter update remains thread-safe because the threads increment the same index in a deterministic manner.
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
