1. fail-fast Iterators in Java

As the name suggests fail-fast Iterators fail as soon as they realized that structure of Collection has been changed since iteration has begun. Structural changes mean adding, removing or updating any element from the collection while one thread is Iterating over that collection. 

The fail-fast behavior is implemented by keeping a modification count and if iteration thread realizes the change in modification count it throws ConcurrentModificationException.

fail-safe Iterator in java

Contrary to fail-fast Iterator, 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 and that’s why they are called as fail-safe iterator. Iterator of CopyOnWriteArrayList is an example of fail-safe Iterator also iterator written by ConcurrentHashMap keySet is also fail-safe iterator and never throw ConcurrentModificationException in Java.

50% LikesVS
50% Dislikes

Leave a Reply

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