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.
Here, we will discuss more about fail safe and fail fast in java❓. Are you ready❓
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
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
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 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
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 Java. You can refer to similar articles for more information.