Sunday, 30 July 2017

Why iterator is fail fast in java?

Iterator is considered fail-fast
Reason:  
It is so because iterator will fail immediately if it senses that the Collection on which it is iterating currently is about to get modified by another thread or by itself. Here modification means addition, deletion or updating of element. And this modification may result in non-deterministic behavior at an undetermined time in future. In such cases, iterator fails by throwing  ConcurrentModificationException.

Let's look at example that shows iterator's fail-fast nature:
package FailFastIterator;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class FailFastItr {

      public static void main(String[] args) {
            List<String> rajneeshList = new ArrayList<String>();
            rajneeshList.add("Java");
            rajneeshList.add("C++");
            rajneeshList.add("Python");

            Iterator<String> itr = rajneeshList.iterator();

            while(itr.hasNext()){
                  String token = itr.next();
                  System.out.println(token);
                  if(token.equals("Python")){
                        rajneeshList.remove(token);  //trying to remove while iteration is going on...
                  }                
            }
            System.out.println("After modification :"+rajneeshList);

      }


}
OUTPUT:

Java
C++
Python
Exception in thread "main" java.util.ConcurrentModificationException
      at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
      at java.util.ArrayList$Itr.next(Unknown Source)
      at FailFastIterator.FailFastItr.main(FailFastItr.java:18)




In the above code you can see that as Collection thread tries to remove element while iteration is on, iterator immediately fails by throwing ConcurrentModificationException. 

You can notice here that even it doesn't print,

System.out.println("After modification :"+rajneeshList);

which is outside while loop and fails immediately at the time of Collection modification. 




You may also like to read about:


No comments:

Post a Comment

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
If you are looking for a reference book on java then we recommend you to go for → Java The Complete Reference
Click on the image link below to get it now.