Member-only story
Difference Between Fail-Fast and Fail-Safe Iterators in Java
🔒 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 modified (
remove()
was called). - Java’s fail-fast mechanism throws
ConcurrentModificationException
to prevent unpredictable behavior.
What is a Fail-Safe Iterator?
A Fail-Safe Iterator is an iterator that does not throw an exception if the collection is modified during iteration. Instead, it iterates over a copy of the collection.
Key Characteristics
Fail-Safe Example with ConcurrentHashMap
import java.util.concurrent.ConcurrentHashMap;
public class FailSafeExample {
public static void main(String[] args) {
ConcurrentHashMap<Integer, String> map = new ConcurrentHashMap<>();
map.put(1, "Amit")…