This post will discuss the fail-fast iterator and fail-safe iterator in Java.

Fail Fast Iterator in Java

If a thread modifies the collection’s structure, 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 throw ConcurrentModificationException are known as fail-fast iterators, as they fail quickly and cleanly, rather than risking arbitrary, non-deterministic behavior later.

For example, the following methods 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 a new copy of the original collection.

CopyOnWriteArrayList is a thread-safe variant of the 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]

That’s all about the fail-fast iterator and fail-safe iterator in Java.