代码:
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());
}
}
当我运行此代码时,出现以下异常:
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)
这一行是 CountUpdater.java:58 :
for(Map.Entry<Integer, DealCountUpdater> e:new HashMap<Integer,DealCountUpdater>(dealCountMap).entrySet()){
我用谷歌搜索了这个程序,我知道我可以使用 ConcurrentHashMap
而不是普通的 HashMap
,
但我想知道,为什么我使用:
new HashMap<Integer,DealCountUpdater>(dealCountMap)
为HashMap创建新实例,仍然抛出ConcurrentModificationException
?
如何通过不使用ConcurrentHashMap
来修复它?
感谢您的帮助:)
最佳答案
原因是这样的:
- 您可以通过在构造函数中传递另一个 HashMap (H2) 来创建新的 HashMap (H1)。
- 在 H1 的构造函数中,它尝试迭代 H2 的元素,以添加自身。
- 当步骤 2 中的迭代正在进行时,其他一些线程修改了 H2。因此ConcurrentModificationException。
不使用ConcurrentHashMap如何解决?
- 进行外部同步
- 按照描述使用复制写入映射 here .
但我仍然建议使用 ConcurrentHashMap,除非你确实有你的理由。
关于java - java HashMap中的ConcurrentModificationException程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5100398/