Java Thread Race Condition
Consider the following code. After the main method executes, the final values in the counts array are not guaranteed to be 2000 for each element. Which statement best explains why the expected values might not be achieved?
public class AtomicMistake {
private int[] counts = new int[2];
public void incrementBoth() {
counts[0]++;
counts[1]++;
}
public static void main(String[] args) {
AtomicMistake am = new AtomicMistake();
Runnable task = () -> {
for (int i = 0; i < 1000; i++) {
am.incrementBoth();
}
};
Thread t1 = new Thread(task);
Thread t2 = new Thread(task);
t1.start();
t2.start();
}
}
A
The increments on counts[0] and counts[1] are not atomic, leading to race conditions where some increments may be lost.
B
The array is too small to support two separate threads modifying its values concurrently.
C
The issue is solely due to the multiplication of thread contexts, not the atomicity of operations.
D
The Java memory model automatically ensures atomicity for simple arithmetic on array elements.
Question Leaderboard
| Rank | |||||
|---|---|---|---|---|---|
| #1 | tykenjcruz | 1 | 1 | 0m 00s | 100 |
| #2 | bommasam000 | 3 | 5 | 4m 39s | 1 |
| #3 | lightingstrikes1342 | 0 | 1 | 0m 00s | -10 |
| #4 | geethasailaja | 1 | 1 | 4m 52s | -192 |
| #5 | y.seong2027 | 1 | 2 | 158h 43m | -571,342 |
Items per page:
10
1 – 5 of 5
APFIVE