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