Thursday, June 15, 2017

What is a ConcurrentModificationException can anyone explain this to me in depth.

If any one ask you what is a ConcurrentModificationException ?
The straight forward answer is "It is thrown only when you are trying to iterate through a collection like list/map and at the same time you are making changes to the collection" 
then ConcurrentModificationException   will be thrown.

humm that's its
Are you willing to know whats happening behind the scenes, if interested continue reading.

Every collection in Java List/Map maintains a transient variable modCount.
modCount is the count howmany times the structure of the collection List/Map has been changes.

Every entry to List or every put operation on Map will increment the modCount by one.




There is one more variable expectedModCount 
expectedModCount which is initialized to the modCount while the iterator is created.

Later on, during every iteration, the iterator verifies if the expectedModCount is same as the modCount of the collection it is iterating over. A mismatch means that the collection
has been modified during the life cycle of the iterator and a ConcurrentModificationException is thrown.






Note 
If you have a Map and you are just changing the value of the Map this will not result in the ConcurrentModificationException as the structure of the Map is not changes

Where as if you are trying to update both the key and value of a Map then in this case ConcurrentModificationException will be thrown.

while (it1.hasNext()) 
{
 String key = it1.next();
   if (key.equals("3")) {
myMap.put(key + "new", "new3");  //Line 1
myMap.put(key, "new3");  //Line 2
    }


}


In above code Line 1 will result in a ConcurrentModificationException as the structure of the map is being changes

Line 2 will not result in ConcurrentModificationException  as the structure of the Map is not changed

1 comment:

  1. http://www.javaranch.com/journal/2002/08/mapinterface.html

    ReplyDelete

java-8-streams-map-examples

package com.mkyong.java8; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.List; im...