Shared Array Modification in Threads
Consider the following Java code snippet. Which statement best describes a potential concurrency-related problem that could occur when this code is executed?
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
The concurrent modification of the array during iteration can lead to unpredictable behavior or logical errors.
B
Enhanced-for loops automatically synchronize access to arrays, so no issue arises.
C
Assigning to the first element during iteration will certainly raise an ArrayIndexOutOfBoundsException.
D
The computeSum method is thread-safe because the local variable sum is confined to each thread.
Question Leaderboard
Not enough data yet to show leaderboard.
