Wednesday 23 July 2014

ConcurrentModificationException

This exception thrown when concurrent modification of an object occurs, when such modification is not permissible. 

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();
        }
    }
}

When you tries to run the program, ConcurrentModificationException thrown, since After the iterator is created, if you tries to add/remove elements to/from the collection, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException.

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