Table of contents
1.
Introduction
2.
What is Fail-Safe?
2.1.
Working of Fail Safe
3.
What is Fail Fast ?
3.1.
Working of Fail Fast
4.
Difference Between Fail-Safe And Fail-Fast Iterator In Java
5.
When to use fail-safe and fail-fast iterators? 
6.
Frequently Asked Questions
6.1.
When to use fail safe iterator?
6.2.
What is a concurrent modification?
6.3.
How does the fail-fast iterator discover that the internal structure has changed?
6.4.
What are the issues associated with fail safe iterators?
7.
Conclusion
Last Updated: Jan 15, 2025
Easy

Fail Safe and Fail Fast Iterator in Java

Author Akshat
1 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Java fail safe and fail fast iterators are used to loop across collection objects. If the collection's structure changes, fail fast iterators immediately throw ConcurrentModificationException. When iterating over a collection that has undergone structural change, fail safe iterators do not throw any exceptions.

In Java, fail-safe and fail-fast iterators are crucial concepts for managing collections during iteration. Fail-fast iterators immediately throw a ConcurrentModificationException when the collection is structurally modified, ensuring data integrity. On the other hand, fail-safe iterators operate on a copy of the collection, allowing seamless iteration despite modifications. This article explores their differences, functionality, and use cases.

What is Fail Safe and Fail Fast Iterator in Java?

Also See, Multithreading in java, and Duck Number in Java.

What is Fail-Safe?

When iterating over a collection that has undergone structural change, fail-safe iterators do not throw any exceptions. They are known as fail-safe iterators because they operate on a copy of the collection rather than the original collection. Examples of fail-safe iterators include ConcurrentHashMap and the iterator on CopyOnWriteArrayList.

Working of Fail Safe

The java SE specs do not utilize the term fail safe, a frequently used concept. This phrase serves as a comparison between the Fail Fast and Non-Fail Fast Iterators. The internal collection (object array) is copied by these iterators, which then iterate over the copied collection. The copied collection is the one that is impacted by any structural changes made to the iterator, not the original collection. Thus, the original collection has not changed structurally.

import java.util.concurrent.CopyOnWriteArrayList;   
import java.util.Iterator;   
class FailSafeDemo {   
    public static void main(String args[])   
    {   
        CopyOnWriteArrayList<Integer> list   
            = new CopyOnWriteArrayList<Integer>(new Integer[] { 2, 8, 10, 12 });   
        Iterator it = list.iterator();   
        while (it.hasNext()) {   
            Integer i = (Integer)it.next();   
            System.out.println(i);   
            if (i == 8)   
                list.add(16);
        }   
    }   
}   
You can also try this code with Online Java Compiler
Run Code

Output -

2
8
10
12

What is Fail Fast ?

Java iterators are used to loop through Collection objects. If the collection has undergone structural modification, Fail-Fast iterators immediately throw ConcurrentModificationException. While a thread is iterating over a collection, structural modification is the addition or removal of any element from that collection. A couple of examples of fail-fast iterators are the ArrayList and HashMap classes.

Working of Fail Fast

Fail-fast iterators use an internal flag called modCount, which is updated every time a collection is modified, to determine if the collection has been structurally modified or not. When they retrieve the next value (by using the next() function), fail-fast iterators check the modCount flag. If they discover that the modCount has changed since this iterator was generated, they issue a ConcurrentModificationException.

import java.util.HashMap;   
    import java.util.Iterator;   
    import java.util.Map;   
public class FailFast {  
        public static void main(String[] args)   
        {   
            Map<String, String> studentName = new HashMap<String, String>();   
            studentName.put("Rohan Sharma", “Delhi”);   
            studentName.put("Rahul Kumar", "Mumbai");   
            studentName.put("Aditya Das", "Kolkata");   
            Iterator iterator = studentName.keySet().iterator();   
            while (iterator.hasNext()) {   
                System.out.println(studentName.get(iterator.next()));   
                studentName.put("Ritish Sharma", "Hyderabad");   
            }   
        }   
    }   
You can also try this code with Online Java Compiler
Run Code

Output -

Delhi
Exception in thread "main" java.util.ConcurrentModificationException
at java.base/java.util.HashMap$HashIterator.nextNode(HashMap.java:1511)
at java.base/java.util.HashMap$KeyIterator.next(HashMap.java:1534)
at FailFast.main(FailFast.java:13)

Difference Between Fail-Safe And Fail-Fast Iterator In Java

You should experiment with examples using both conventional collections like ArrayList and concurrent collections like CopyOnWriteArrayList. Let's examine some of the most important differences between fail-safe And fail-fast iterators :

  1. Fail fast ConcurrentModficationException is thrown by the iterator whenever it detects a structural change in the collection while iterating, thus changing the modCount variable that Iterator is holding. A fail-fast iterator, however, does not throw CME.
  2. Fail-safe iterators traverse a clone or view of the original collection, whereas fail-fast iterators traverse the original collection class. Because of this, they fail to notice any modification to the original collection classes, which opens the possibility of using outdated data.
  3. Iterators returned by concurrent collection classes like CopyOnWriteArrayList or CopyOnWriteArraySet are fail safe, whereas iterators from Java 1.4 Collection classes like ArrayList, HashSet, and Vector are fail-fast.
  4. Returned by synchronized iterator In Java, collections are fail-fast, whereas concurrent collections' iterators are fail safe.
  5. While fail-safe iterators are weekly consistent, fail-fast iterators only work with live data and become invalid when the data is changed.

Let’s look into some more differences between fail-safe and fail-fast in Java according to some base of comparison.

Base of ComparisonFail Fast IteratorFail Safe Iterator
ExceptionWhen changing the object during the iteration process, it throws a ConcurrentModificationException.There is no exception thrown by it.
Clone ObjectThroughout the iteration process, no duplicated objects are produced.Each iteration produces a copy or clone of the original object.
Memory utilizationLow memory is needed for the process.During the process, more memory is needed.
ModificationIt doesn't permit changes during iteration.Throughout the iteration process, it permits modification.
PerformanceIt is fast.It is slightly slower.
ExamplesHashMap, ArrayList, Vector, HashSet, etcCopyOnWriteArrayList, ConcurrentHashMap, etc.

 

When to use fail-safe and fail-fast iterators? 

Let us see when to use fail-safe and fail-fast iterators in Java. If you don't care if the collection is changed while iterating, use a fail-safe iterator instead of a fail-fast. Unfortunately, depending on whatever Collection class you use, you cannot select a fail-safe or fail-fast iterator.

Only the concurrent collections introduced in JDK 1.5, such as CopyOnWriteArrayList and CopyOnWriteArraySet, provide fail-safe iteration, while the majority of JDK 1.4 collections, such as HashSet, Vector, and ArrayList, have fail-fast iterators.

Additionally, utilize the iterator's remove() method rather than the remove method given by Collection classes, such as ArrayList or HashSet, as doing so will lead to a ConcurrentModificationException.

Frequently Asked Questions

When to use fail safe iterator?

If you don't care if the Collection is changed while iterating, use a fail safe iterator

What is a concurrent modification?

Concurrent modification occurs when one thread alters the collection's structure while one or more other threads are iterating through it.

How does the fail-fast iterator discover that the internal structure has changed?

The internal data structure (object array) was directly read by the iterator. While iterating through the collection, it is important to avoid changing the internal data structure or object array.

What are the issues associated with fail safe iterators?

When using a fail-safe iterator, the data being read may not always match what is currently in the original data structure.

Conclusion

Fail-safe and fail-fast iterators in Java offer distinct advantages depending on the requirements of your application. While fail-fast iterators ensure real-time accuracy and data consistency, fail-safe iterators provide robustness against concurrent modifications. Understanding their mechanisms helps developers choose the appropriate iterator for effective collection management. For deeper insights, refer to our additional resources and tutorials.

Recommended article:

Live masterclass