Thursday, June 3, 2010

Difference between Fail fast and Fail safe Iterators

Iterators can be either fail fast or fail safe. Depending on the underlying implementation of the Iterator (Fail Fast), a ConcurrentModificationException is thrown if the Collection is modified while Iterating over the data structure.

The fail safe iterator (CopyOnWriteArrayList ) makes a copy of the internal array data structure and uses it to iterate over the elements. This prevents any concurrent modification exceptions from being thrown if the underlying data structure changes

The CopyOnWriteArrayList does not fail when the internal structure changes, but where as ArrayList does. The CopyOnWriteArrayList is A thread-safe variant of ArrayList in which all mutative operations (add, set, and so on) are implemented by making a fresh copy of the underlying array.

3 comments:

  1. Nice post Anil, clear and concise on explaining difference between failsafe and failfast Iterator. Just one question though Apart form CopyOnWriteArrayList which other collection has failsafe Iterator ?

    Thanks
    Javin
    How HashMap works in Java

    ReplyDelete
  2. what is fail fast? what is fail safe? what is difference between fail fast and fail safe? this is very important interview question. you can find the details on http://www.itsoftpoint.com/?page_id=2736

    ReplyDelete