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:
packageFailFastIterator;
importjava.util.ArrayList;
importjava.util.Iterator;
import java.util.List;
public class FailFastItr {
      public static void main(String[] args) {
            List<String> rajneeshList = newArrayList<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:
  • Can we call run() directly on thread without calling start?
  • Class variable vs instance variable
  • iterator vs list iterator
  • Why String is immutable in java?
  • What is marker interface?
  • Why java is secure as programming language?
  • Collection vs Collections
  • Class variable vs instance variable

Source link

Why iterator is fail fast in java?

Leave a Reply

Your email address will not be published. Required fields are marked *