Fail-fast
is a property of software with the help of which it can stop the normal
execution of the program if a failure situation occurs. A fail-fast system is
designed to immediately report any failure or condition that is likely to lead
to failure. Fail fast property makes our software more robust. We can easily
find the bugs and fix them.
In
Java, iterator is considered as fail fast. If an iterator has been created on a
collection of objects and some other thread in the program tries to modify the same
collection, a concurrent modification exception will be thrown. If after the
creation of the iterator on a collection, the collection is modified by any
method other than the iterators remove or add method, it will always throw the concurrent
modification exception. Suppose we have created an iterator over Array List in
java and while traversing the list in while loop we try to remove element with
iterator.remove() method, it will give the “java.lang.IllegalStateException”
exception. We can use the remove method of ListIterator in the while loop.
To
illustrate, Java iterator is fail fast see the below example
import java.util.*;
public class demoIterator
{
public static void main(String s[])
{
ArrayList al = new ArrayList();
//Adding Elements to the Arraylist
al.add("fffff");
al.add("bbbbb");
al.add("ddddd");
al.add("ccccc");
al.add("aaaaa");
//Printing all the element of ArrayList
System.out.println("All Elements
in the ArrayList"+al);
//Traverse the elements in ArrayList
one by one with the help of Iterator
System.out.println("Start
traversing elements of list one by one");
Iterator it = al.iterator();
while(it.hasNext())
{
//In Iterator, List can be only be
traversed in forward with Iterator.next();
it.remove();
System.out.println(it.next());
}
}
}
Output of
the program:
Exception in thread
"main" java.lang.IllegalStateException
All Elements in the
ArrayList[fffff, bbbbb, ddddd, ccccc, aaaaa]
Start traversing elements
of list one by one
at
java.util.AbstractList$Itr.remove(AbstractList.java:356)
at
demoIterator.main(demoIterator.java:22)
No comments:
Post a Comment