Sunday 20 October 2019

Difference between fail-safe and fail-fast iterator in Java

        In the current interview topic, we will discuss the difference between fail safe and fail fast iterators in Java. Basically this question is related to ConcurrentModificationException, means what are the scenario to throw this exception. The above iterator one it will throw exception and another one doesn't throw, this is the main difference. We can discuss few more differences and with examples as follows

Related topicDifference between HashSet and TreeSet in Java

Difference between fail-fast and fail-safe iterator:-
diff. between fail-fast and fail-safe
Difference between fail-fast and fail-safe iterator

Example of fail-fast iterator:-

         As we see the difference between fail-fast and fail-safe in the diagram, the mainly difference is to throw the ConcurrentModificationException. In any type of Collection, internally it will use an array of objects to store the elements. While iterating the collection, we can not modify the existing array. Internally collection will use flag to indicate whether the given collection is modified or not. Based on this flag it will throw the exception if flag is true.

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:-

           The fail-safe iterator doesn't throw any exception if the collection is modified while iterating over it. Internally it will copy the original collection object, and iterate over the copied collection object. Due to this internal behavior, if any modification done on collection, it doesn't impact on iterator.

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

2 comments: