ConcurrentModificationException
JavaERRORCommonConcurrency
Collection modified during iteration
Quick Answer
Use Iterator.remove() to delete during iteration, or use list.removeIf() to batch-remove elements.
What this means
Thrown by an iterator when the underlying collection is modified structurally during iteration outside of the iterator's own remove() method.
Why it happens
- 1Calling list.remove() inside a for-each loop over the same list
- 2Two threads iterating and mutating the same collection
Fix
Use removeIf (Java 8+)
Use removeIf (Java 8+)
list.removeIf(s -> s.isEmpty()); // safe — no CME
Why this works
removeIf uses the iterator internally, so structural modifications are tracked correctly.
Code examples
Triggerjava
for (String s : list) {
if (s.isEmpty()) list.remove(s); // ConcurrentModificationException
}Safe with Iteratorjava
Iterator<String> it = list.iterator();
while (it.hasNext()) {
if (it.next().isEmpty()) it.remove();
}Thread-safe with CopyOnWriteArrayListjava
List<String> safe = new CopyOnWriteArrayList<>(list);
for (String s : safe) { /* safe to remove from safe */ }Same error in other languages
Sources
Official documentation ↗
Java SE Documentation
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev