Fail-Fast Iterators and ConcurrentModificationException
35 min · Intermediate
A fail-fast iterator stops with a ConcurrentModificationException (CME) as soon as it notices that its collection changed behind its back. The classic trigger is a single thread removing from a list inside a for-each loop, and interviewers love to ask why it happens and how to fix it.
Topics in this lesson
- modCount: why the exception is thrown
- Predict the output: changing a collection inside for-each
- Safe removal: Iterator.remove and removeIf
- Fail-fast vs fail-safe iterators
- Trap: removing the second-to-last element does not throw
Interview questions this lesson answers
- What is ConcurrentModificationException?
- Why is ConcurrentModificationException thrown?
- Can it happen in a single-threaded program?
- What is a structural modification?
- How do you remove elements safely while iterating?
- Why does Iterator.remove not throw?
- What happens if you call Iterator.remove twice in a row?
- Why is removeIf better than a manual loop?
- What is the difference between fail-fast and fail-safe iterators?
- How does CopyOnWriteArrayList avoid ConcurrentModificationException?
Sign in free to continue this lesson
Create a free account to read every lesson, practise with the exercises and keep track of your progress.