Fail-Fast vs Fail-Safe Iterators in Java
Fast recall
Quick revision
Core answer
Whether you understand how Java collections handle concurrent modification during iteration, and which collections use which strategy
Thinking ConcurrentModificationException only happens with multiple threads — it also occurs in a single thread if you modify a collection while iterating with a for-each loop
Explain the modCount mechanism behind fail-fast, show the single-threaded case, and explain why Iterator.remove() is safe but collection.remove() during iteration is not
Interview-ready guide
Interview answer
Fail-fast iterators throw ConcurrentModificationException the moment they detect structural modification — even in single-threaded code.
How fail-fast works:
- Collection tracks modifications via a
modCountfield — incremented on every add/remove/clear - Iterator records
modCountat creation and checks on everynext()— mismatch throws immediately
Common single-threaded trap:
for (String s : list) { list.remove(s); }throws immediately —list.remove()changesmodCountbehind the iterator's back- Safe alternatives:
Iterator.remove()(modifies through the iterator, keepsmodCountin sync) orlist.removeIf()
Weakly consistent iterators (concurrent collections):
ConcurrentHashMapandCopyOnWriteArrayListnever throwConcurrentModificationExceptionConcurrentHashMap: reflects some concurrent changes but not necessarily all — safe from exceptions, not a point-in-time snapshotCopyOnWriteArrayList: operates on a snapshot captured at creation — guaranteed stable view
I recommend removeIf() for single-threaded filtered removal and concurrent collections when multiple threads need to modify during iteration.
Fail-Fast vs Fail-Safe Iterators in Java
Direct Answer
Fail-fast iterators (ArrayList, HashMap) throw ConcurrentModificationException immediately if the collection is structurally modified during iteration. Fail-safe iterators (CopyOnWriteArrayList, ConcurrentHashMap) work on a copy or snapshot, so modifications during iteration don't throw exceptions but may not reflect the latest changes.
Common Mistakes & Pitfalls
Thinking ConcurrentModificationException only happens with multiple threads — it also occurs in a single thread if you modify a collection while iterating with a for-each loop
Check your understanding
Answer these without looking back at the article.
- Why does Iterator.remove() not throw ConcurrentModificationException?
- What is the performance impact of CopyOnWriteArrayList?
- How does ConcurrentHashMap achieve weak consistency?
Related interview prep categories
1Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.