Monday 11 July 2011

ConcurrentModificationException - Fail-fast Operations


Most of the time we use ArrayList ,add objects,remove and iterate through them in the List.Go through the following code.



The above code will result in 
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(Unknown Source)
at java.util.AbstractList$Itr.next(Unknown Source)
at CSSCreator.main(CSSCreator.java:16)

This is because of fail-fast operation .Note that this exception does not always indicate that an object has been concurrently modified by a different thread. If a single thread issues a sequence of method invocations that violates the contract of an object, the object may throw this exception. For example, if a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this exception.


The best way to avoid ConcurrentModificationException is to use iterator while you have modifications to be done for the arraylist which you are iterating.

Using iterator in the following way also ends up with ConcurrentModificationException.


The right way of using it will be as follows and it makes sense because the iterator object knows where it is in the list as the list is being scanned.

 I had some tough time with this ConcurrentModificationException and thought of sharing(may be useful to some one at some point of time).....  

cheers ;-)

4 comments:

  1. This one is really good one dude.

    ReplyDelete
  2. why can't we use like this,

    for(int i: numList)
    {
    numList.remove();
    }

    instead of giving index for remove() method?

    ReplyDelete
  3. @Dinakar

    I guess
    numList.remove()... no such method yet ;-).
    you shud mention the index or object to remove.

    Thanks!!

    ReplyDelete