Saturday 19 July 2014

Fail Fast Iterator

fail-fast Iterators fail as soon as they realized that structure of Collection has been modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException.

Java Specification said like below
The fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.

Example
import java.util.*;

public class ListEx{
    static ArrayList<Integer> myList = new ArrayList<> ();
    
    public static void main(String args[]){
        
        for(int i=0; i<10; i++)
            myList.add(i);
        
        Iterator<Integer> myIter;
        myIter = myList.iterator();
        
        System.out.println("Adding element after creating iterator");
        myList.add(345);
        
        while(myIter.hasNext()){
            myIter.next();
        }
    }
}

Output
Adding element after creating iterator
Exception in thread "main" java.util.ConcurrentModificationException
 at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:886)
 at java.util.ArrayList$Itr.next(ArrayList.java:836)
 at ListEx.main(ListEx.java:18)
Java Result: 1




                                                             Home

No comments:

Post a Comment