Java Thread Race Condition
In the context of concurrent execution, why might the counts array not reflect the expected values after both threads execute?
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 issue is solely due to the multiplication of thread contexts, not the atomicity of operations.
C
The Java memory model automatically ensures atomicity for simple arithmetic on array elements.
D
The array is too small to support two separate threads modifying its values concurrently.
Question Leaderboard
| Rank | |||||
|---|---|---|---|---|---|
| #1 | tykenjcruz | 1 | 1 | 0m 00s | 100 |
| #2 | lightingstrikes1342 | 0 | 1 | 0m 00s | -10 |
| #3 | bommasam000 | 2 | 4 | 4m 15s | -75 |
| #4 | geethasailaja | 1 | 1 | 4m 52s | -192 |
| #5 | y.seong2027 | 1 | 2 | 158h 43m | -571,342 |
APFIVE