When does ConcurrentModificationException happen, and how do fail-fast and fail-safe iterators differ?
Short answer
A fail-fast iterator remembers how many times the collection was modified (modCount) when created. If the collection is changed not through that iterator, next() throws ConcurrentModificationException, even with just one thread.
3 points to say:
- Removing inside for-each is the most common cause.
- Use
removeIforiterator.remove(). - Fail-fast does not protect multithreading.
Keep reading the deep dive
Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.