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:

  1. you create new hashmap(h1) passing hashmap(h2) in constructor.
  2. in constructor fo h1, tries iterate through elements of h2, add in itself.
  3. while iteration in step 2 going on, other thread modifies h2. hence concurrentmodificationexception.

how solve without using concurrenthashmap?

  1. do external synchronization
  2. use copy-n-write map described here.

but still suggest using concurrenthashmap, unless have reasons.


Comments

Popular posts from this blog

linux - Mailx and Gmail nss config dir -

c# - Is it possible to remove an existing registration from Autofac container builder? -

php - Mysql PK and FK char(36) vs int(10) -