Fail-Fast vs Fail-Safe Iterators
Understand ConcurrentModificationException, fail-fast behavior, and when to use snapshot iterators.
Fail-Fast vs Fail-Safe Iterators
Java iterators are categorized by their behavior when the underlying collection is modified during iteration: fail-fast iterators throw immediately; fail-safe iterators continue on a snapshot.
Fail-Fast Iterators
Most standard Java collections (ArrayList, HashMap, TreeSet) use fail-fast iterators. They track a modCount — a mutation counter. Any structural modification while iterating triggers ConcurrentModificationException.
import java.util.*;
List<String> list = new ArrayList<>(List.of("a", "b", "c"));
try {
for (String s : list) {
list.add("x"); // structural modification — throws!
}
} catch (ConcurrentModificationException e) {
System.out.println("ConcurrentModificationException caught!");
}
// Same for HashMap, TreeMap, HashSet, etc.All lessons in this course
- The Iterable and Iterator Contracts
- Implementing a Custom Iterator
- ListIterator and Bidirectional Traversal
- Fail-Fast vs Fail-Safe Iterators