Wednesday, December 26, 2012

java.util.ConcurrentModificationException False belief

Dear all,


I faced the exception

java.util.ConcurrentModificationException

Immediately I started thinking ..., since two different functions{A() and B()} are executing parallel, some critical section variable might be accessed at the same time by both functions A() and B().

So to solve the issue, I used java function 'synchronized() {  } ' blocks inside both the functions A() and B().  But surprisingly the error was not solved.

Thanks to the link

http://stackoverflow.com/questions/8189466/java-util-concurrentmodificationexception

which told me that, the concurrent exception happens because of the Iterator I used in one of the function A().

Consider the program

 ------------------------------------------------------------------------------

set= myhashmap.entrySet();

i=set.Iterator();

while (i.hasNext())

      {

       myhashmap.remove(datanode);//This causes problem

        }

  --------------------------------------------------------------------------------------------------

 

'i' has already Iterator set values and pointers/ memory locations assigned to it.  But when you remove an item from hashmap, the 'i' is not getting updated(i =set.Iterator() is not called inside while).  So when while(i.hasNext () ) is checking for datanode location, it finds that somebody else has already removed/modified the data in that location.  So it thinks that Some body(some other program) is accessing the memory(critical section) alloted to it.  Hence shouts ConcurrentModificationException