Wednesday, 26 August 2015

Fail Safe Iterator

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.

Two  issues associated with Fail Safe Iterator are :

1. Overhead of maintaining the copied data structure i.e memory.

2. Fail safe iterator does not guarantee that the data being read is the data currently in the original data structure.

According to Oracle docs , fail safe iterator is ordinarily too costly, but may be 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 "snapshot" style iterator method uses a reference to the state of the array at the point that the iterator was created.

This array never changes during the lifetime of the iterator, so interference is impossible and the iterator is guaranteed not to throw ConcurrentModificationException.

The 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.

How it deal?

While creating the iterator, take the snapshot of collections and don’t care that the collection is modified at iteration time.

Set, add and remove methods of iterator throws the UnsupportedOperationException.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...