Monday, December 14, 2009

java.util.ConcurrentModificationException and ConcurrentHashMap

ConcurrentModificationException comes whenever modification happened in the time of iteration operation happening in the Collections objects like HashMap, AbstractList and etc.,

Eventually within the iterator loop, if we try to add item to Map also we get this exception.

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;


public class concurrentMaptest {

public static void main(String[] args) throws Exception{
final Map<Integer,Integer> m= new HashMap<Integer, Integer>();
for(int i=0;i<1000;i++)
{
m.put(i, i);
}

new Thread()
{
@Override
public void run() {
Iterator<Entry<nteger,Integer>> it=m.entrySet().iterator();
while(it.hasNext())
{
Entry<nteger,Integer> ent=it.next();

m.put(ent.getKey()+1, ent.getValue());
}
}
}.start();

new Thread()
{
@Override
public void run() {
Iterator<Entry<nteger,Integer>> it=m.entrySet().iterator();
while(it.hasNext())
{
it.next();
it.remove();
}
}
}.start();

Thread.sleep(1000);

System.out.println(m);
}
}



Following exception trace will be the outcome of this program

Exception in thread "Thread-0" java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextEntry(Unknown Source)
at java.util.HashMap$EntryIterator.next(Unknown Source)
at java.util.HashMap$EntryIterator.next(Unknown Source)
at concurrentMaptest$1.run(concurrentMaptest.java:24)


java.util.concurrent.ConcurrentHashMap



java.util.concurrent.ConcurrentHashMap is an utility class which follows complete spec of HashMap( except null key is not allowed) and makes lock-free threadsafe collection operations.


For instance, change the HashMap declaration line as below and run the program, we won't face any Exception

final Map<Integer,Integer> m= new ConcurrentHashMap<Integer, Integer>(); 



No comments:

Post a Comment

Recent Posts

Unix Commands | List all My Posts

Texts

This blog intended to share the knowledge and contribute to JAVA Community such a way that by providing samples and pointing right documents/webpages. We try to give our knowledege level best and no guarantee can be claimed on truth. Copyright and Terms of Policy refer blogspot.com