The Plain Picture#
You're counting people in a queue by walking along it. If people keep leaving and joining while you walk, your count is nonsense. A strict counter stops and complains the moment the queue changes behind their back.
The Real Names#
An
Iteratorwalks through a collection:hasNext(),next(), andremove()(removes the last element returned, safely). The for-each loop uses an iterator behind the scenes.Java's standard collections have fail-fast iterators: if the collection is structurally modified (elements added or removed) during iteration by anything other than the iterator itself, the next
next()throwsConcurrentModificationException. They detect it with an internal modification counter (modCount) that the iterator compares on each step.
Under the Hood#
List<Integer> scores = new ArrayList<>(List.of(40, 180, 90, 200, 60));
for (Integer s : scores) if (s < 100) scores.remove(s); // modifying while for-each iterates
// ConcurrentModificationExceptionTwo correct ways:
Iterator<Integer> it = scores.iterator();
while (it.hasNext()) if (it.next() < 100) it.remove(); // remove THROUGH the iterator
// [180, 200]
scores.removeIf(s -> s < 100); // simplest: removeIf with a condition
// [180, 200](A third option: loop backwards by index and call remove(i) — removing later elements doesn't shift earlier ones.)
Despite the name, ConcurrentModificationException usually has nothing to do with threads — it's almost always one thread modifying a
collection inside its own loop. For real multi-threaded access, use concurrent collections (Concurrency).
Check yourself
3 questionsWhat does "fail-fast iterator" mean?
Show answerHide answer
It throws ConcurrentModificationException as soon as it detects the collection was structurally modified outside the iterator.
Give two correct ways to remove elements while looping.
Show answerHide answer
iterator.remove(), removeIf(condition) (or looping backwards by index).
Does ConcurrentModificationException mean you have a threading bug?
Show answerHide answer
Usually not — typically it's the same thread modifying the collection inside a for-each loop.