Shared Array Modification in Threads
What concurrency-related problem is most likely in this code snippet?
public class ConcurrentSum {
private int[] numbers = {1, 2, 3, 4, 5};
public void computeSum() {
int sum = 0;
for (int num : numbers) {
sum += num;
numbers[0] = 0; // modifying the array during iteration
}
System.out.println(sum);
}
public static void main(String[] args) {
ConcurrentSum cs = new ConcurrentSum();
Thread t1 = new Thread(() -> cs.computeSum());
Thread t2 = new Thread(() -> cs.computeSum());
t1.start();
t2.start();
}
}
A
Assigning to the first element during iteration will certainly raise an ArrayIndexOutOfBoundsException.
B
The computeSum method is thread-safe because the local variable sum is confined to each thread.
C
Enhanced-for loops automatically synchronize access to arrays, so no issue arises.
D
The concurrent modification of the array during iteration can lead to unpredictable behavior or logical errors.
Question Leaderboard
Not enough data yet to show leaderboard.
APFIVE