Question
What causes java.util.ConcurrentModificationException when modifying collections in Java?
List<String> myList = new ArrayList<>();
myList.add("A");
myList.add("B");
for (String item : myList) {
myList.remove(item); // This line will throw ConcurrentModificationException
}
Answer
The java.util.ConcurrentModificationException is a runtime exception that occurs when one thread attempts to modify a collection while another thread is iterating over it, or when a collection is structurally modified during iteration in a single-threaded context. Understanding how to manage collection modifications is essential for smooth application functionality.
// Using Iterator for safe removal
yourList.removeIf(item -> item.equals("B")); // Prefer this instead of modifying while iterating
Causes
- Modifying a collection (e.g., adding or removing elements) while iterating over it using an iterator or enhanced for loop.
- Using collection classes like ArrayList in which modifications during iteration are not supported.
Solutions
- Use the Iterator interface's remove() method instead of using the collection's remove() method directly during iteration.
- Consider using concurrent collection classes like CopyOnWriteArrayList or ConcurrentHashMap which are designed to handle modifications in multi-threaded situations.
- Collect items to be removed in a separate List, and remove them after the iteration completes.
Common Mistakes
Mistake: Using a for-each loop when modifying a collection.
Solution: Switch to an Iterator and use its remove() method for safe element removal.
Mistake: Not synchronizing access to a shared collection in multi-threaded apps.
Solution: Use synchronized blocks or concurrent collection classes to manage access.
Helpers
- ConcurrentModificationException Java
- Java Collection modification
- Java iterator exception
- fix ConcurrentModificationException in Java
- Java collection thread safety