Java Collections support two types of iterators, first one is fail fast and the second is fail safe. These play a vital role when it comes to exception handling in Java. In this article on ‘Fail Fast And Fail Safe Iterators’, we will be analysing the working of the two iterators as well as the essential difference between them.
Following are the pointers to be discussed in this article:
Before getting into a detailed explanation, lets familiarize ourselves with the concept of Concurrent Modification.
Concurrent Modification
When a single thread (or multiple threads), iterates over a collection, it can change the structure of the collection, either by adding or deleting the element in the collection, or by updating the value of the element at a particular position. This process is known as concurrent modification.
Let us quickly take a look at the two System that concern above topic, before getting into the details of the same,
Fail Fast Sysetm:
A system is labelled a fail fast system, if it shuts down immediately after the occurrence of an error. The operations are instantly aborted and the failures or the errors are exposed.
Fail Safe System:
A system is labelled a fail safe system, if they continue to operate even after a fault or an error has occurred. They don’t abort an operation and hide the errors instead of exposing them.
Iterators in java allow us to traverse over the Collection objects. The iterators returned by the Collection are either fail fast or fail safe in nature.
Fail Fast Iterator
Fail fast iterators in Java disallow any type of structural modification to a collection while iterating over it. Structural Modification includes adding, removing or updating any element in the collection while iterating over it. The iterator throws a ConcurrentModificationException, if a collection is structurally modified during the process of iteration.
However, it must be noted that if an item is removed using the iterators own method i.e. the remove() method, no exception is thrown. It is an entirely safe process. make Sure you have java installed on your system
Example of Fail Fast Iterator:
import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class FailFastExample { public static void main(String[] args) { Map monthIndex = new HashMap(); monthIndex.put("1", "January"); monthIndex.put("2", "February"); monthIndex.put("3","March"); Iterator iterator = monthIndex.keySet().iterator(); while (iterator.hasNext()) { System.out.println(monthIndex.get(iterator.next())); //adding an element to Map //exception will be thrown on next call //of next() method. monthIndex.put("4", "April"); } } }
Output:
Exception in thread “main” java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextEntry(Unknown Source)
Now let us go ahead and take a look at Fail Safe Iterator,
Fail Safe Iterator
Unlike Fail Fast iterators, Fail Safe iterators don’t throw any exceptions if the collection is modified during the process of iteration. This is due to the fact that they iterate on the clone of the collection, instead of the actual collection. The structural modifications done on the actual collection goes unnoticed by them.
However, it should be noticed that there is no such thing as a truly Fail Safe Iterator. It would be appropriate to term it as Weakly-Consistent. This simply means that if a Collection is modified during the process of iteration, what the Iterator sees is weakly guaranteed. This behavior differs for different collections and is documented in Javadocs.
Example of Fail Safe Iterator:
public class FailSafeExample { public static void main(String[] args) { ConcurrentMap monthIndex = new ConcurrentHashMap(); monthIndex.put("1", "January"); monthIndex.put("2", "February"); monthIndex.put("3","March"); Iterator iterator = monthIndex.keySet().iterator(); while (iterator.hasNext()) { System.out.println(monthIndex.get(iterator.next())); monthIndex.put("4", "April"); } } }
Output:
- January
- February
- March
Finally in this article we would be comparing these iterators,
Differences: Fail Fast And Fail Safe Iterator
Given below are the essential differences between the two iterators:
Parameters | Fail Fast Iterator | Fail Safe Iterator |
Throw ConcurrentModification Exception | Yes, they throw CocurrentModificationExcepti-on if a collection is modified while iterating over it. | No, they do not throw any exception if a collection is modified while iterating over it. |
Clone the Collection | No, they use original collection to traverse over the elements. | Yes, they use the copy of the original collection to traverse. |
Memory Overhead | No, they don’t require extra memory. | Yes, they require extra memory to clone the collection. |
Examples | HashMap, Vector,ArrayList,HashSet | CopyOnWriteArrayList |
These iterators both unique and much needed in the versatile language of java. Although fail safe has a comforting ring to it, the fail fast iterator proves to be robust.
This brings to the end of this article. in case you wish to learn more then check out the Java Training by Edureka. Edureka’s Java J2EE and SOA training and certification course is designed to give you a head start into Java programming and train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.
Got a question for us? Please mention it in the comments section of this “Fail Fast vs Fail Safe” blog and we will get back to you as soon as possible.