22.1 Fail Fast and Fail Safe Iterators

"Fail-Fast iterators immediately throw ConcurrentModificationException if a collection is modified while iterating over it.

Where as Fail-Safe iterators don’t throw any exceptions if a collection is modified while iterating over it. Because, they operate on the clone of the collection, not on the actual collection."

"The major difference is fail-safe iterator doesn’t throw any Exception, contrary to fail-fast Iterator.This is because they work on a clone of Collection instead of the original collection and that’s why they are called as the fail-safe iterator."


Fail Fast: ArrayList, HashMap, etc.

To know whether the collection is modified or not, they use an internal flag called modCount which is updated each time a collection is modified.

Iterator<Integer> it = list.iterator();
while (it.hasNext())
{
            Integer integer = (Integer) it.next();
            list.add(8457);      //This will throw ConcurrentModificationException
}

Fail Safe: ConcurrentHashMap, CopyOnWriteArrayList

CopyOnWriteArrayList<Integer> list = new CopyOnWriteArrayList<Integer>(new Integer[] { 1, 3, 5, 8 });
Iterator itr = list.iterator(); 
while (itr.hasNext()) { 
              Integer no = (Integer)itr.next(); 
              System.out.println(no); 
              if (no == 8) 

                // This will not print, 
                // hence it has created separate copy 
                list.add(14); 
}
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<String, Integer>(); 
while (it.hasNext())
{
     String key = (String) it.next();
     System.out.println(key+" : "+map.get(key));
     // This will reflect in iterator. 
     // Hence, it has not created separate copy 
     map.put("FIVE", 5);
}

results matching ""

    No results matching ""