Java ArrayList Concurrent Modification
What potential runtime error is present in the removeIfCondition method of the code segment shown?
import java.util.*;
public class IteratorIssue {
private List<Integer> list = new ArrayList<>();
public void removeIfCondition() {
if(!list.isEmpty()) {
for(Integer num : list) {
if(num < 5) {
list.remove(num);
}
}
}
}
public void addValue(int value) {
list.add(value);
}
public static void main(String[] args) {
IteratorIssue ii = new IteratorIssue();
ii.addValue(3);
ii.addValue(7);
new Thread(() -> ii.removeIfCondition()).start();
}
}
A
The for-each loop automatically synchronizes on the list, negating any potential issues.
B
The issue arises from a race condition between addValue and removeIfCondition, which is guaranteed by the unsynchronized if check.
C
The if statement’s early check makes the loop iterate over an empty collection, so no removal occurs.
D
Removing elements from an ArrayList while iterating over it without proper synchronization can lead to ConcurrentModificationException or unpredictable behavior.
Question Leaderboard
Not enough data yet to show leaderboard.
APFIVE