Fail-Fast vs Fail-Safe Iterators
Fail-fast iterators throw ConcurrentModificationException when a collection changes during iteration; fail-safe (weakly consistent) iterators work on a snapshot or tolerate changes. Interviewers ask how it works and how to remove elements safely.
What you will learn
- Explain modCount and ConcurrentModificationException
- Remove elements safely during iteration
- Know which collections are fail-safe
Key concepts
modCount
ArrayList and HashMap count structural changes. The iterator remembers the count when it starts and throws ConcurrentModificationException if it changes outside the iterator. It is a best-effort bug detector, not a thread-safety guarantee.
Fail-safe / weakly consistent
CopyOnWriteArrayList iterates over a snapshot; ConcurrentHashMap iterators tolerate concurrent changes. Neither throws.
Step by step
Safe ways to remove
// 1. Iterator.remove
for (Iterator<Order> it = orders.iterator(); it.hasNext();) {
if (it.next().isCancelled()) it.remove();
}
// 2. removeIf (simplest)
orders.removeIf(Order::isCancelled);
// 3. Build a new list
List<Order> active = orders.stream().filter(o -> !o.isCancelled()).toList();Examples
A single thread can trigger it
List<String> list = new ArrayList<>(List.of("a", "b", "c"));
for (String s : list) {
if (s.equals("a")) list.remove(s); // throws ConcurrentModificationException on the next step
}Practise it
Try these without looking back. If you can explain each one out loud, you are ready for this question.
- Explain why removing the second-to-last element in a for-each loop does not throw.
- Modify a HashMap while iterating its entrySet safely.
Interview questions
What interviewers ask next on this topic. Answer out loud first, then open the model answer.
Does ConcurrentModificationException mean multiple threads were involved?
No. It most often happens in one thread that changes a collection inside a for-each loop. With multiple threads you need a concurrent collection, not just this check.
Summary
Fail-fast iterators detect structural changes through modCount and throw; concurrent collections iterate on snapshots or tolerate changes. Remove with Iterator.remove or removeIf.
Stuck on this one? Talk to Sumit.
Keys: F focus mode · ← → previous / next topic · Esc leave focus