multithreading - ConcurrentModificationException Program in java HashMap -
code:
map<integer,dealcountupdater> dealcountmap=new hashmap<integer,dealcountupdater>(); public void update(){ for(map.entry<integer, dealcountupdater> e:new hashmap<integer,dealcountupdater>(dealcountmap).entryset()){//line:58 system.out.println(e.hashcode()); } }
when run code,get below exception:
java.util.concurrentmodificationexception @ java.util.hashmap$hashiterator.nextentry(hashmap.java:793) @ java.util.hashmap$entryiterator.next(hashmap.java:834) @ java.util.hashmap$entryiterator.next(hashmap.java:832) @ java.util.hashmap.putallforcreate(hashmap.java:435) @ java.util.hashmap.<init>(hashmap.java:225) @ org.my.tuan.count.countupdater.update(countupdater.java:58) @ org.my.tuan._maintainer.run(tuansched.java:110)
this line countupdater.java:58 :
for(map.entry<integer, dealcountupdater> e:new hashmap<integer,dealcountupdater>(dealcountmap).entryset()){
i google program,i know can using concurrenthashmap
instead of plain hashmap
,
but want know ,why using :
new hashmap<integer,dealcountupdater>(dealcountmap)
to create new instance hashmap,still throw concurrentmodificationexception
?
how fix not using concurrenthashmap
?
thanks :)
the reason this:
- you create new hashmap(h1) passing hashmap(h2) in constructor.
- in constructor fo h1, tries iterate through elements of h2, add in itself.
- while iteration in step 2 going on, other thread modifies h2. hence concurrentmodificationexception.
how solve without using concurrenthashmap?
- do external synchronization
- use copy-n-write map described here.
but still suggest using concurrenthashmap, unless have reasons.
Comments
Post a Comment