Clean • Professional
Iterators in Java behave differently when the underlying collection is modified during iteration. This difference creates two important types:

Understanding these behaviors is very important for interviews and real-world multithreaded applications.
A Fail-Fast Iterator immediately throws a ConcurrentModificationException if the collection is structurally modified during iteration (other than using iterator.remove()).
Fail-fast iterators are used in normal Java collections:
These belong to the java.util package.
Fail-fast iterators use two variables:
modCount → tracks structural changes in the collectionexpectedModCount → value stored by iterator at the startWhen iterating:
If (modCount != expectedModCount)
throw ConcurrentModificationException
So any structural modification during iteration breaks synchronization and throws an exception.
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
for (String s : list) {
if (s.equals("B")) {
list.remove(s); // Structural modification
}
}
}
}
Output:
Exception in thread "main" java.util.ConcurrentModificationException
Use iterator.remove(), not list.remove():
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String s = it.next();
if (s.equals("B")) {
it.remove(); // Safe
}
}
This avoids fail-fast exception because removal happens through the iterator itself.
ConcurrentModificationExceptionA Fail-Safe Iterator does not throw exceptions even if the collection is modified during iteration.
Because it works on a copy (snapshot) of the underlying collection.
Fail-safe iterators come from the java.util.concurrent package:
These collections are designed for multithreading.
ConcurrentModificationExceptionimport java.util.concurrent.*;
public class Main {
public static void main(String[] args) {
CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
list.add("A");
list.add("B");
for (String s : list) {
list.add("C"); // No exception
}
System.out.println(list);
}
}
Output:
[A, B, C, C]
ConcurrentModificationException| Feature | Fail-Fast Iterator | Fail-Safe Iterator |
|---|---|---|
| Works on | Original collection | Copy of collection |
| Throws exception? | Yes, ConcurrentModificationException | No |
| Safety | Not thread-safe | Thread-safe |
| Performance | Faster | Slower (due to copy) |
| Used in | Normal Collections | Concurrent Collections |
Fail-Fast
Original Collection
↓
Iterator (checks modCount)
↓
Modification → Exception
Fail-Safe
Original Collection → Snapshot Copy
↓
Iterator
(Modifications allowed, no exception)
iterator.remove() prevents fail-fast errors