Are you taking CLEP classes? Try clep.ai
| preferred AP College board partner for AP classes
hard Solved by 2 students

Java ArrayList Concurrent Modification

Mark
< Prev
Next >

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 issue arises from a race condition between addValue and removeIfCondition, which is guaranteed by the unsynchronized if check.

B

Removing elements from an ArrayList while iterating over it without proper synchronization can lead to ConcurrentModificationException or unpredictable behavior.

C

The for-each loop automatically synchronizes on the list, negating any potential issues.

D

The if statement’s early check makes the loop iterate over an empty collection, so no removal occurs.

Hint
Did You Know?
Explain Why
Explain All Answers
Check Answer
Show Correct Answer
Report Question

Question Leaderboard

Not enough data yet to show leaderboard.

AI Tutor

How can I help?

APFIVE © 2020.
Email: apfive@apfive.org|Privacy Policy|