Why This Happens
Java collections use a fail-fast mechanism that detects structural modification during iteration. If you add or remove elements from a list while a for-each loop is running, the iterator detects the change and throws this exception. This can happen in single-threaded code too.
The Problem
List<String> names = new ArrayList<>(List.of("Alice", "Bob", "Charlie"));
for (String name : names) {
if (name.startsWith("B")) {
names.remove(name); // ConcurrentModificationException
}
}The Fix
List<String> names = new ArrayList<>(List.of("Alice", "Bob", "Charlie"));
Iterator<String> it = names.iterator();
while (it.hasNext()) {
if (it.next().startsWith("B")) {
it.remove(); // Safe removal via iterator
}
}
// Or: names.removeIf(name -> name.startsWith("B"));Step-by-Step Fix
- 1
Identify the modification during iteration
Find the loop that iterates over the collection and the line inside it that modifies the same collection.
- 2
Determine the modification type
Check if you are adding, removing, or replacing elements during iteration.
- 3
Use safe modification patterns
Use Iterator.remove(), Collection.removeIf(), or collect items to remove in a separate list and remove after iteration.
Bugsly catches this automatically
Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.
Try Bugsly free