ConcurrentModificationException and the situations in which this exception is thrown.A fail-fast iterator throws a ConcurrentModificationException if the underlying collection is structurally modified while it is being iterated (except through the iterator's own remove() method). In contrast, a fail-safe iterator does not throw this exception because it iterates over a copy (or snapshot) of the collection rather than the original collection.
Now, let's explore the key differences between fail-fast and fail-safe iterators in detail, along with practical examples.
Related topic - Difference between HashSet and TreeSet in Java
Difference between fail-fast and fail-safe iterator:-
![]() |
| Difference between fail-fast and fail-safe iterator |
Example of fail-fast iterator:-
As shown in the diagram, the primary difference between fail-fast and fail-safe iterators lies in how they handle
ConcurrentModificationException.Most Java collections store their elements internally using data structures such as arrays, linked lists, or hash tables. While iterating over a collection, modifying the underlying collection directly is generally not allowed, as it can lead to unpredictable behavior.
Fail-fast iterators internally maintain a modification count (modCount) to detect structural changes to the collection. When an iterator is created, it stores the current value of modCount as the expected modification count. During iteration, the iterator continuously compares the current modCount with the expected value. If they differ, it indicates that the collection has been structurally modified outside the iterator, and a ConcurrentModificationException is thrown.
FailFastIteratorExample.java,
package com.example.demo;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class FailFastIteratorExample {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
iterator.next();
list.add("C");
}
}
}
Output:-
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
at java.util.ArrayList$Itr.next(Unknown Source)
at com.example.demo.FailFastIteratorExample.main(FailFastIteratorExample.java:17)
Example Of fail-safe iterator:-
A fail-safe iterator does not throw a
ConcurrentModificationException if the collection is modified while it is being iterated. Instead, it operates on a copy (or snapshot) of the original collection rather than the collection itself.Because the iterator traverses the copied collection, any modifications made to the original collection after the iterator is created do not affect the iteration. As a result, changes to the original collection are not reflected in the current iteration, and no ConcurrentModificationException is thrown.
FailSafeIteratorExample.java,
package com.example.demo;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
public class FailSafeIteratorExample {
public static void main(String[] args) {
List<String> list = new CopyOnWriteArrayList<String>();
list.add("A");
list.add("B");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
iterator.next();
list.add("C");
}
list.forEach(str -> System.out.println(str));
}
}
Output:-
A
B
C
C
Related Posts:-
1) Collection Hierarchy in Java
2) Collection Interview Questions and Answers in Java(List,Map & Set)
3) How to iterate the TreeMap in reverse order in Java
4) How to Remove duplicates from ArrayList in Java
5) Internal Implementation of TreeMap in Java
6) Internal implementation of ArrayList in Java
7) Internal Implementation of LinkedList in Java
8) Difference between HashSet and TreeSet in Java

BA Exam Result - BA 1st Year, 2nd Year and 3rd Year Result
ReplyDeleteBsc Exam Result - Bsc 1st Year, 2nd Year and 3rd Year Result
Very good collection of Java interview questions to know before attending interview.
ReplyDelete