What is difference between fail safe iterator and fail fast iterator

Before understanding the difference between fail safe iterator and fail fast iterator we need to understand what is concurrent modification

What is concurrent modification

When multiple threads are iterating over a collection and if any thread modifies the collection structure by deleting,adding or modifying the collection values, it is known as concurrent modification. So while one thread is trying to read the collection, some other thread is modifying it at the same time which can result in inconsistent data inside the collection

Fail fast Iterator

Fail fast iterator while iterating through the collection , instantly throws Concurrent Modification Exception if there is structural modification of the collection . Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

Example of Fail fast iterator is HashMap

 public static void main(String[] args)
    {
        Map<String,String> premiumPhone = new HashMap<String,String>();
        premiumPhone.put("Apple", "iPhone");
        premiumPhone.put("HTC", "HTC desire");
        premiumPhone.put("Samsung","Galaxy");
 
        Iterator iterator = premiumPhone.keySet().iterator();
 
        while (iterator.hasNext())
        {
            System.out.println(premiumPhone.get(iterator.next()));
            premiumPhone.put("Sony", "Xperia Z");
        }
 
    }

Above code will throw ConcurrentModificationException

Fail Safe Iterator

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. So , original data structure remains structurally unchanged .Hence , no ConcurrentModificationException throws by the fail safe iterator.

Example of Fail safe iterator is ConcurrentHashmap

 public static void main(String[] args)
    {
        ConcurrentHashMap<String,String> premiumPhone = 
                               new ConcurrentHashMap<String,String>();
        premiumPhone.put("Apple", "iPhone");
        premiumPhone.put("HTC", "HTC one");
        premiumPhone.put("Samsung","S5");
 
        Iterator iterator = premiumPhone.keySet().iterator();
 
        while (iterator.hasNext())
        {
            System.out.println(premiumPhone.get(iterator.next()));
            premiumPhone.put("Sony", "Xperia Z");
        }
 
    }

Output would be

S5
HTC one
iPhone

Uday Ogra

Connect with me at http://facebook.com/tendulkarogra and lets have some healthy discussion :)

You may also like...

Leave a Reply

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