Member-only story
Difference Between Fail-Fast and Fail-Safe Iterators in Java
4 min readApr 5, 2025
🔒 This is a Medium member-only article. If you’re not a Medium member, you can read the full article for free on my blog: fail-fast vs fail-safe Iterators in Java.
What is a Fail-Fast Iterator?
A Fail-Fast Iterator is an iterator that immediately fails (throws an exception) if it detects any structural modification of the collection after the iterator was created.
Key Characteristics
Fail-Fast Example with ArrayList
import java.util.*;
public class FailFastExample {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Amit");
names.add("Sneha");
names.add("Rahul");
Iterator<String> iterator = names.iterator();
while (iterator.hasNext()) {
String name = iterator.next();
if (name.equals("Sneha")) {
names.remove(name); // Modifying the collection during iteration
}
}
}
}
Output:
Exception in thread "main" java.util.ConcurrentModificationException
⚠️ Why the Error?
- The iterator detects that the list was structurally…