Difference between fail-fast and fail-safe Iterator has become one of the favorite question for many interviewers as it has a slight flavors of concurrency. Java provides the iterator to iterate the objects in the Collection. The rule is that the Collection should not be altered when iterating, if modified you will get the ConcurrentModificationException.
Fail-Fast Iterator
As the name sounds the Iterator will fail as soon as the it encounters a change in the collection. What ever the change it may be adding, update or removal of any object in the collection will throw the ConcurrentModificationException. Lets look it in the below example.
import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class FailFastIterator { public static void main(String args[]) { List al = new ArrayList(); al.add("1"); al.add("2"); al.add("3"); al.add("4"); al.add("5"); int indexFlag=0; Iterator it = al.iterator(); while(it.hasNext()) { indexFlag++; if(indexFlag==2) { al.remove(indexFlag); } System.out.println(it.next()); } } }
This will throw ConcurrentModificationException as the iteration has started and we are removing the element of the ArrayList .
Exception in thread "main" java.util.ConcurrentModificationException at java.util.AbstractList$Itr.checkForComodification(Unknown Source) at java.util.AbstractList$Itr.next(Unknown Source) at FailIterator.main(FailIterator.java:20)
Fail-Safe Iterator
Whereas the fail-safe iterator will not throw any exception when the collection such as CopyOnWriteArrayList and ConcurrentHashMap is modified. As it iterates on the copy of the collection.
import java.util.Iterator; import java.util.concurrent.CopyOnWriteArrayList; public class FailSafeIterator { public static void main(String args[]) { CopyOnWriteArrayList ca = new CopyOnWriteArrayList(); ca.add("1"); ca.add("2"); ca.add("3"); ca.add("4"); ca.add("5"); int indexFlag=0; Iterator it = ca.iterator(); while(it.hasNext()) { indexFlag++; if(indexFlag==2) { ca.remove(indexFlag); } System.out.println(it.next()); } } }
This will not throw any exception.
How to Safely remove object from the collection while Iterating?
If you wish to remove the Object from the collection , instead of directly removing from the collection , you can use the remove() provided by the iterator.
import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class FailIterator { public static void main(String args[]) { List al = new ArrayList(); al.add("1"); al.add("2"); al.add("3"); al.add("4"); al.add("5"); System.out.println("List before Iteration "+al); int indexFlag=0; Iterator it = al.iterator(); while(it.hasNext()) { it.next(); indexFlag++; if(indexFlag==2) { it.remove(); } } System.out.println("List after Iteration"+al); } }
This will not throw any exeception and you get the below output.
List before Iteration [1, 2, 3, 4, 5] List after Iteration[1, 3, 4, 5]
Leave a Reply