Fail Fast Vs Fail Safe Iterator In Java

Fail fast iterator while iterating through the collection , instantly throws Concurrent Modification Exception if there is structural modification  of the collection.

 Fail Safe Iterator makes copy of the internal data structure (object array) and iterates over the copied data structure.Any structural modification done to the iterator affects the copied data structure.
Fail Fast Iterator Fail Safe Iterator
Throws ConcurrentModification Exception. Does not throws ConcurrentModification Exception.
Does not clone object . Clones objects.
No memory Overhead occurs. Memory Overhead occurs.
Examples:HashMap,Vector ,ArrayList, HashSet. Examples:CopyOnWriteArrayList,
ConcurrentHashMap

Concurrent Modification

When one or more thread is iterating over a collection, and in between if one thread changes the structure of the collection (either adding a element or by deleting a element or by updating a value  in the collection) is known as Concurrent Modification.

Fail-fast Iterator Example:

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class FailFastExample
{
    
    
    public static void main(String[] args)
    {
        Map mapExample = new HashMap();
        mapExample.put("key1", "value1");
        mapExample.put("key2", "value2");
        mapExample.put("key3","value3");
        
        Iterator iterator = mapExample.keySet().iterator();
        
        while (iterator.hasNext())
        {
            System.out.println(mapExample.get(iterator.next()));
            mapExample.put("key4", "value4");
        }
        
    }
    
}
Output:
value1
Exception in thread “main” java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextEntry(Unknown Source)
at java.util.HashMap$KeyIterator.next(Unknown Source)
at FailFastExample.main(FailFastExample.java:20)

Fail-Safe Iterator Example:

import java.util.concurrent.ConcurrentHashMap;
import java.util.Iterator;


public class FailSafeExample
{
    
    
    public static void main(String[] args)
    {
        ConcurrentHashMap mapExample = 
                               new ConcurrentHashMap();
        mapExample.put("key1", "value1");
        mapExample.put("key2", "value2");
        mapExample.put("key3","value3");
        
        Iterator iterator = mapExample.keySet().iterator();
        
        while (iterator.hasNext())
        {
            System.out.println(mapExample.get(iterator.next()));
            mapExample.put("key4", "value4");
        }
        
    }
    
}

Output:

value1
value2
value3
value4