java HashMap中的ConcurrentModificationException程序

Koe*_*err 1 java multithreading java.util.concurrent

代码:

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());
    }
}
Run Code Online (Sandbox Code Playgroud)

当我运行此代码时,出现以下异常:

java.util.ConcurrentModificationException
        at java.util.HashMap$HashIterator.nextEntry(HashMap.java:793)
        at java.util.HashMap$EntryIterator.next(HashMap.java:834)
        at java.util.HashMap$EntryIterator.next(HashMap.java:832)
        at java.util.HashMap.putAllForCreate(HashMap.java:435)
        at java.util.HashMap.<init>(HashMap.java:225)
        at org.my.tuan.count.CountUpdater.update(CountUpdater.java:58)
        at org.my.tuan._Maintainer.run(TuanSched.java:110)
Run Code Online (Sandbox Code Playgroud)

这一行是 CountUpdater.java:58 :

for(Map.Entry<Integer, DealCountUpdater> e:new HashMap<Integer,DealCountUpdater>(dealCountMap).entrySet()){
Run Code Online (Sandbox Code Playgroud)

我谷歌这个程序,我知道我可以使用一个ConcurrentHashMap而不是一个普通的HashMap

但我想知道,为什么我使用:

new HashMap<Integer,DealCountUpdater>(dealCountMap)
Run Code Online (Sandbox Code Playgroud)

为 HashMap 创建新实例,仍然抛出ConcurrentModificationException

如何通过不使用来修复它ConcurrentHashMap

感谢帮助 :)

Sur*_*ran 5

原因是这样的:

  1. 您可以通过在其构造函数中传递另一个 hashmap( H2 ) 来创建一个新的 hashmap( H1 ) 。
  2. 在 H1 的构造函数中,它尝试遍历 H2 的元素,以添加自身。
  3. 在步骤 2 中的迭代进行时,其他一些线程修改了 H2。因此ConcurrentModificationException

如何在不使用ConcurrentHashMap 的情况下解决它?

  1. 做外部同步
  2. 使用此处所述的 copy-n-write 映射。

但我仍然建议使用 ConcurrentHashMap,除非你真的有你的理由。