1.

Explain fail-fast and fail-safe iterators. Differentiate between them.

Answer»

If the collection's structure is changed, Fail-Fast iterators immediately throw ConcurrentModificationException. While a thread is iterating over a collection, structural ALTERATION includes adding or deleting any element. Fail-safe Iterator classes include ArrayList Iterator and HashMap Iterator. Fail-fast iterators use an internal indicator CALLED modCount, which is updated each time a collection is modified, to determine if the collection has been structurally modified or not. When a fail-fast iterator gets the next item (through the next() method), it checks the modCount flag, and if it discovers that the modCount has been changed after the iterator was generated, it throws a ConcurrentModificationException.

If a collection is structurally updated while iterating over it, fail-safe iterators don't throw any exceptions. Because they operate on a clone of the collection rather than the original collection, they are REFERRED to as fail-safe iterators. Fail-safe Iterators include the CopyOnWriteArrayList and ConcurrentHashMap classes.

Fail-FastFail-Safe
These types of iterators do not allow MODIFYING the collection while iterating over it.These types of iterators allow modifying the collection while iterating over it.
It throws ConcurrentModificationException if the collection is modified while iterating over it.No exception is thrown if the collection is modified while iterating over it.
It uses the original collection while traversing the elements.It uses a copy of the original collection while traversing over it.
No extra memory is required in this CASE.Extra memory is required in this case.


Discussion

No Comment Found