Fail Fast and Fail Safe Iterators in Java

Iterators in Java are used to iterate over Collections. Iterators are basically of 2 types.

1)Fail Fast Iterators.

2)Fail Safe Iterators.

Fail Fast:

Fail Fast iterators are the iterators which throw an exception if it is iterating over a particular collection and some other thread modifies that collection. It will throw an ConcurrentModificationException if it encounters this situation. Iterators on ArrayList and Hashmap are examples of Fail Fast Iterator.

Fail Safe:

First of all there is nothing like Fail Safe Iterator. To differentiate it from Fail Fast we say Fail safe. Fail Safe iterators are the iterators which creates a copy of the collection if it is iterating over a particular collection. It will not throw an ConcurrentModificationException if another thread modifies the collection since it would be operating on the copy of that collection. That’s why it is called Fail Safe. Iterators on CopyOnWriteArrayList, ConcurrentHashMap classes are examples of fail-safe Iterator. A

Working of Fail Fast Iterator:

To check if an collection is modified, fail-fast iterators use an internal counter called modCount which increments every time when the collection gets modified by an thread. Fail-fast iterators continuosly checks the modCount flag whenever it calls the next() method to fetch the value and if it finds that the value of the counter has been changed or you can say incremented from the previous value then it throws ConcurrentModificationException at that point.

Let’s look at the code implementation of it below:

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
  
public class FailFastImpl {
    public static void main(String[] args)
    {
        
        Map<String, String> empNames = new HashMap<String, String>();
        empNames.put("A001", "James");
        empNames.put("A002", "John");
        empNames.put("A003", "David");
  
        Iterator iterator = empNames.keySet().iterator();
  
        while (iterator.hasNext()) {
            System.out.println(empNames.get(iterator.next()));
            //Below entry is added during  iteration. So Exception would be Thrown when next is called
            empNames.put("A004", "Glen");
        }
    }
}

O/P:

James
Exception in thread "main" java.util.ConcurrentModificationException

Let’s look at the code implementation of a FailSafe Iterator. We use an CopyOnWriteArrayList to show it.


import java.util.concurrent.CopyOnWriteArrayList;
import java.util.Iterator;
  
class FailSafeImpl {
    public static void main(String args[])
    {
        CopyOnWriteArrayList<String> empList
            = new CopyOnWriteArrayList<String>(new String[] { "James", "David", "Glen" });
        Iterator itr = empList.iterator();
        while (itr.hasNext()) {
            String name = (Integer)itr.next();//Line 4
            System.out.print(name);//Line 5
            if (name.equalsIgnoreCase("Glen"))//Line 6
                empList.add("John");//Line 7
        }
    }
}

O/P:

James David Glen

If you see above output , then no exception was thrown and John was not printed.

Because Iterator working on the CopyOnWriteArrayList class is a Fail Safe Iterator. So it was ierating on the copy of the list and added element on that copy.

Hence it was not printed and no concurrent modification exception was thrown.