Fail Fast Iterator vs Fail Safe Iterator in Java

In this post, we will we discuss about fail fast iterator and fail safe iterator in Java.

 

1. Fail Fast Iterator in Java

If a thread modifies the structure of a collection i.e. add elements to it or remove elements from it, while another thread (or same thread) is iterating over it, ConcurrentModificationException may be thrown by the iterator. Iterator implementations that throws ConcurrentModificationException are known as fail fast iterators, as they fail quickly and cleanly, rather that risking arbitrary, non-deterministic behavior later.

For example, below functions will throw a ConcurrentModificationException as they permit concurrent modification on an ArrayList instance:

 

1. Using an Iterator:

The iterators returned by ArrayList iterator() and listIterator() methods are fail fast: if the list 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.

 

Download   Run Code

Output:

Exception in thread “main” java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
    at java.util.ArrayList$Itr.next(ArrayList.java:851)
    at FailFast.filterList(Main.java:14)
    at FailFast.main(Main.java:32)

 

2. Using For loop:

 

3. Using Java 8 Stream:

 

Fail Safe Iterator in Java

Iterator implementations that don’t throw ConcurrentModificationException when a thread modifies the structure of a collection while another thread or same thread is iterating over it, are known as fail safe iterators as they work on new copy of the original collection.

CopyOnWriteArrayList is a thread-safe variant of ArrayList in which all mutative operations (add, set, and so on) are implemented by making a new copy of the underlying array.

 

Download   Run Code

Output:

[BLUE, YELLOW]

 
 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz