Monday, November 26, 2012

Fail-fast vs fail-safe iterators

Fail-fast iterators
"Fail-fast iterator" means that if the collection class is structurally modified at any time after the Iterator is created, in any way except through the Iterator's own remove or add methods, the Iterator will throw a ConcurrentModificationException.

 Throwing ConcurrentModificationException is not granted, so you have NOT to relay on it. ConcurrentModificationException is used to show the developer that his/her classes are not synced.

Most ifiterators in Java are fail-fast, these found in classes:
- LinkedList
- ArrayList
- Vector

Fail-safe iterators
Fail-safe iterator doesn't throw any Exception if Collection is modified structurally.
While one thread is Iterating over it because they work on clone of Collection instead of original collection. The consequences of using fail-safe iterators (an old snapshot of elements in the collection) are:
 - the cloning of the collection (in the iterator) is costy operation;
 - the operations on the iterator are faster, because they do not need syncronization, so they never block.
 - more efficient than alternatives when traversal operations vastly outnumber mutations, and is useful when you cannot or don't want to synchronize traversals, yet need to preclude interference among concurrent threads.

The fail-safe iterator will not reflect additions, removals, or changes to the list since the iterator was created. Element-changing operations on iterators themselves (remove, set, and add) are not supported. These methods throw UnsupportedOperationException. If you need such operations, use the collection object directly.

Fail-safe iterators are:
 - Iterator of class java.util.concurrent.CopyOnWriteArrayList
 - Iterator of class java.util.concurrent.ConcurrentHashMap

No comments:

Post a Comment