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.
What is fail safe?
6.2.
When to use fail safe iterator?
6.3.
What is a concurrent modification?
6.4.
How does the fail-fast iterator discover that the internal structure has changed?
6.5.
What are the issues associated with fail safe iterators?
7.
Conclusion
Last Updated: Mar 27, 2024
Easy

What is Fail Safe and Fail Fast Iterator in Java?

Author Akshat
0 upvote
gp-icon
Data structures & algorithms (Beginner to Intermediate)
Free guided path
13 chapters
99+ problems
gp-badge
Earn badges and level up

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);
        }   
    }   
}   

 

Output -

2
8
10
12
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

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");   
            }   
        }   
    }   

 

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 Comparison Fail Fast Iterator Fail Safe Iterator
Exception When changing the object during the iteration process, it throws a ConcurrentModificationException. There is no exception thrown by it.
Clone Object Throughout the iteration process, no duplicated objects are produced. Each iteration produces a copy or clone of the original object.
Memory utilization Low memory is needed for the process. During the process, more memory is needed.
Modification It doesn't permit changes during iteration. Throughout the iteration process, it permits modification.
Performance It is fast. It is slightly slower.
Examples HashMap, ArrayList, Vector, HashSet, etc CopyOnWriteArrayList, 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

What is 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.

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
  7.  Internal Working of HashMap
  8. Java List Iterator

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.

 

Happy learning, Ninja!🥷

Previous article
Difference Between this and super Keyword in Java
Next article
Enumeration in Java
Guided path
Free
gridgp-icon
Data structures & algorithms (Beginner to Intermediate)
13 chapters
109+ Problems
gp-badge
Earn badges and level up
Live masterclass