library
intermediateFail-Fast vs Fail-Safe Iterators
Understand why ArrayList throws ConcurrentModificationException but ConcurrentHashMap doesn't.
Java collections have two iteration behaviors:
Fail-fast = a security guard who immediately stops you if someone else enters the room during your presentation. Fail-safe = a camera recording — keeps going regardless of who enters, but the recording might miss late arrivals.
Key Concepts
1
Fail-fast iterators (ArrayList, HashMap, HashSet, etc.): throw ConcurrentModificationException immediately when they detect the collection was structurally modified outside the iterator during iteration. They use an internal modification counter (modCount) — if the counter changes between next() calls, the exception is thrown.
2
Fail-safe iterators (ConcurrentHashMap, CopyOnWriteArrayList, etc.): operate on a snapshot or don't track modifications. They never throw ConcurrentModificationException but may not reflect recent changes.
3
ConcurrentHashMap: iterators are weakly consistent — they reflect some but not necessarily all modifications made after the iterator was created. They never throw CME.
4
CopyOnWriteArrayList: the iterator works on a snapshot of the array at creation time. Writes to the list create a new array, so the iterator sees the old version. Good for read-heavy, write-rare scenarios.
5
Note: 'fail-fast' is best-effort — it's not guaranteed. Don't write code that depends on catching ConcurrentModificationException. Use concurrent collections or explicit synchronization instead.
6
Common mistake: modifying a list inside a for-each loop. Use iterator.remove() or collect elements to remove and process after the loop.