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


Exception in thread “main” java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(
    at java.util.ArrayList$
    at FailFast.filterList(
    at FailFast.main(


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



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