Tuesday, 3 November 2015

What is ConcurrentModificationException?


ConcurrentModificationException:- The ConcurrentModificationException has to do with the fail-fast nature of the collection iterators.If an underlying collection is modified outside the remove() method of the iterator while you are iterating through its elements, this will be detected upon the next access and a ConcurrentModificationException will be thrown, thereby causing the iteration to stop.


For example:-


import java.util.ArrayList;  
 import java.util.Iterator;  
 import java.util.List;  
 public class ConcurrentModificationExceptionExample {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           List<String> l=new ArrayList<String>();  
           l.add("Sub");  
           l.add("Mul");  
           l.add("Div");  
           Iterator<String> itr=l.iterator();  
           while(itr.hasNext())  
           {  
                System.out.println(itr.next());  
                l.add("Add");  
           }  
      }  
 }  

Output:-
Sub  
 Exception in thread "main" java.util.ConcurrentModificationException  
      at java.util.AbstractList$Itr.checkForComodification(Unknown Source)  
      at java.util.AbstractList$Itr.next(Unknown Source)  
      at ConcurrentModificationExceptionExample.main(ConcurrentModificationExceptionExample.java:20)  


The above program starts by walking the elements of an iterator but adds an element after printing the first one. As this modifies the underlying collection, the iterator is immediately invalidated such that second call to next() fails.

ConcurrentModificationException is a run-time exception.you don't have to place all your iterating code in try-catch block.

The methods which can cause modification to the Collection interface are :- add(), addAll(), clear(), remove(), removeAll(), retainAll().


Enjoy Reading :)

No comments:

Post a Comment