Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
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: Jul 9, 2024
Easy

Fail Safe and Fail Fast Iterator in Java?

Author Akshat
0 upvote

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.

What is Fail Safe and Fail Fast Iterator in Java?

Here, we will discuss more about fail safe and fail fast in java❓. Are you ready❓

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)


Practice by yourself on java online compiler.

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.

We hope you have understood everything about Fail Safe and Fail Fast in Java. 

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

In this blog, we studied Fail Safe and Fail Fast in JavaYou can refer to similar articles for more information.

  1. Understanding The Java Methods
  2. Abstract Class and Methods in Java
  3. Strings in Java: Part-1
  4. Understanding Java Packages List
  5. Classes and Objects in Java
  6. Super Keyword In Java

You can refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enroll in our courses and refer to the mock test and problems available. Take a look at the interview experiences and interview bundle for placement preparations.

Live masterclass