Why iterator is fail fast in java?
In this chapter of java interview questions, we will learn about:
-
why iterator is fail fast in java?
-
example of fail-fast iterator
-
fail fast vs fail safe
Why iterator is fail fast?
Lets understand why iterator is fail fast in java with example.
Iterator is considered as fail-fast as it immediately throws concurrent modification exception, if it senses that the collection on which it is iterating currently is attempted to be modified by any other thread from outside.
Fail fast features ensures that if iterator feels that modification of collection would result in anamolous behaviour at any point of time in future, it fails immediately.
Example of fail-fast iterator
Given below is a demonstration of fail fast iterator in java:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class FailFastItr {
public static void main(String[] args) {
List
OUTPUT:
Java
C++
Python
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
at java.util.ArrayList$Itr.next(Unknown Source)
at FailFastIterator.FailFastItr.main(FailFastItr.java:18)
fail fast vs fail safe in java
-
fail fast system such as iterators on hashmap fails immediately while iterating over it, in case it feels that some other thread is trying to modify the hashmap by throwing ConcurrentModificationException.
-
fail safe system works on the copy of the system (hashmap) so there is no impact if the original collection or the copy itself is modified while iteration is on.
Would you like to see your article here on tutorialsinhand.
Join
Write4Us program by tutorialsinhand.com
About the Author
Sonu Pandit
I am editor in chief at tutorialsinhand.com responsible for managing, reviewing and sending articles/contents for final approval to get published. Connect with me@https://www.linkedin.com/in/sonu-pandit-a77b471ab/. Join write4us program & share your skill
Page Views :
Published Date :
Dec 21,2020