Sunday 30 July 2017

Why iterator is fail fast in java?

Iterator is considered fail-fast
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>();

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

                  String token =;
                        rajneeshList.remove(token);  //trying to remove while iteration is going on...
            System.out.println("After modification :"+rajneeshList);



Exception in thread "main" java.util.ConcurrentModificationException
      at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
      at java.util.ArrayList$ Source)
      at FailFastIterator.FailFastItr.main(

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:

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.