Fail Fast vs Fail Safe Iterator in Java

Fail Fast vs Fail Safe Iterator in Java

When an iterator is created, either it is directly created on the collection (Fail Fast), or created on a clone of that collection (Fail Safe).This brings below two types of Iterator.

Fail Fast :
As name suggest fail-fast Iterators fail as soon as they realized that structure of Collection has been modified since iteration has begun, if the iterator thread realizes the modification ,then it throws ConcurrentModificationException. Changes can be additions, updation or deletion. This behavior (fail-fast) is implemented by keeping a modification count.

From API
Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs

Example :
Iterators returned by Vector, ArrayList, HashSet , HashMap etc are fail-fast. i.e. most JDK1.4 collections

Output:

Fail Safe :
This iterators doesn’t throw exception if the Collection is modified concurrently. Because these iterators works the clone of the Collection not with the original.

Example : Iterators return by CopyOnWriteArrayList,ConcurrentHashMap (Added in JDK 5)
In the above example if you change HashMap to ConcurrentHashMap things will be fine.

Output :

7 thoughts on “Fail Fast vs Fail Safe Iterator in Java

  1. for CopyOnWriteArrayList the above example will not throw any error but it doest add the +11 to the list. why??
    Im thinking since it creates a new copy of the collection, why not it is happening in case of concurrentHashmap

  2. Hi LakshmiPrasad,
    It will add element in both the cases to the data structure (verify by printing the structure after loop).
    Java docs for each iterator will tell the story.

    ConcurrentHashMap keySet()

    /**
    * Returns a {@link Set} view of the keys contained in this map.
    * The set is backed by the map, so changes to the map are
    * reflected in the set, and vice-versa. The set supports element
    * removal, which removes the corresponding mapping from this map,
    * via the Iterator.remove, Set.remove,
    * removeAll, retainAll, and clear
    * operations. It does not support the add or
    * addAll operations.
    *
    *

    The view’s iterator is a “weakly consistent” iterator
    * that will never throw {@link ConcurrentModificationException},
    * and guarantees to traverse elements as they existed upon
    * construction of the iterator, and may (but is not guaranteed to)
    * reflect any modifications subsequent to construction.
    */

    CopyOnWriteArrayList

    /**
    * Returns an iterator over the elements in this list in proper sequence.
    *
    *

    The returned iterator provides a snapshot of the state of the list
    * when the iterator was constructed. No synchronization is needed while
    * traversing the iterator. The iterator does NOT support the
    * remove method.
    *
    * @return an iterator over the elements in this list in proper sequence
    */
    public Iterator iterator() {
    return new COWIterator
    (getArray(), 0);
    }

  3. The important point for all this discussion is why the iterators are fail fast? I want to know the reason behind their failure. If the collection structure is modified (something added, deleted or changed), why can’t they handle the new structure?

  4. Sandeep,
    Its by design.”Fail fast” means: it may fail … and the failure condition is checked aggressively so that the failure condition is detected before damage can be done.

    Fail Fast Concept in WiKi

  5. Is there any way to make our iterators as fail-safe programatically. If yes, then how?

  6. Bibek,

    I like your answer. In specific, I liked the point you stressed on the error raised by design to ensure that the wrong data is not iterated by mistake. Kudos !!

    Although it is a bit old, I am impressed !! 🙂

    Regards,
    Siva.

Leave a Reply

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

Time limit is exhausted. Please reload the CAPTCHA.