What is fail fast and fail-safe iterator in java?

By | August 14, 2019

In this blog post we will discuss about one of the very important java interview question What is fail fast and fail-safe iterator in java?

Fail-Fast Iterator

  • Iterator fails as soon as it realizes that the structure of the underlying data structure has been modified since the iteration has begun.
  • Structural changes mean adding, removing any element from the collection, merely updating some value in the data structure does not count for the structural modifications.
  • Fail-Fast Iterator is implemented by keeping a modification count and if iterating thread realizes the changes in modification count then it throws ConcurrentModificationException. Most collections in package util.* are fail-fast by Design.

Fail-Safe Iterator

  • Fail-safe Iterator is “Weakly Consistent” and does not throw any exception if collection is modified structurally during the iteration.
  • Such Iterator -may work on clone of collection instead of original collection such as in CopyOnWriteArrayList
  • Most collections under util.concurrent offer fail-safe Iterators to its users and that’s by Design.
  • Fail safe collections should be preferred while writing multi-threaded applications to avoid concurrency related issues.
  • Fail Safe Iterator is guaranteed to list elements as they existed upon construction of Iterator, and may reflect any modifications subsequent to construction (without guarantee).

Let’s understand above points by creating couple of examples:

Example which will throw ConcurrentModificationException known as Fail-Fast Iterators

Above program will throw Exception as below:

Example which will  not throw ConcurrentModificationException known as Fail-Safe Iterators

Above program will produce below output without any Exception: 

You may also like:

What is difference between Iterator and LisIterator?
Why Prime Numbers are considered in writing certain algorithms like hashcode()?
What all collections utilizes hashCode() method in java?
Describe CopyOnWriteArrayList? Where is it used in Java Applications?

That’s all about  What is fail fast and fail-safe iterator in java?
If you have any feedback or suggestion please feel free to drop in blow comment box.

One thought on “What is fail fast and fail-safe iterator in java?

  1. Pingback: Which collections are fail fast in java? – Lusocoder

Leave a Reply

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