[英]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 I run this code,get below exception: 当我运行此代码时,请获取以下异常:
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)
this line is CountUpdater.java:58 : 这行是CountUpdater.java:58:
for(Map.Entry<Integer, DealCountUpdater> e:new HashMap<Integer,DealCountUpdater>(dealCountMap).entrySet()){
I google this program,I know I can using a ConcurrentHashMap
instead of a plain HashMap
, 我谷歌这个程序,我知道我可以使用
ConcurrentHashMap
而不是普通的HashMap
,
but I want to know ,why I using : 但我想知道为什么使用:
new HashMap<Integer,DealCountUpdater>(dealCountMap)
to create new Instance for HashMap,still throw ConcurrentModificationException
? 为HashMap创建新的实例,仍然抛出
ConcurrentModificationException
吗?
how to fix it by not using ConcurrentHashMap
? 如何通过不使用
ConcurrentHashMap
进行修复?
thanks for help :) 感谢帮助 :)
The reason is this: 原因是这样的:
How to solve it without using ConcurrentHashMap ? 不使用ConcurrentHashMap怎么解决?
But I would still suggest using ConcurrentHashMap, unless you really have your reasons. 但是我仍然建议您使用ConcurrentHashMap,除非您确实有自己的理由。
You simply cannot,or should not, modify a hashmap in a thread while another thread is iterating over it. 您根本无法(也不应)在另一个线程对其进行迭代时修改一个线程中的哈希映射。 In such cases, the HashMap iterator will throw a ConcurrentModificationException.
在这种情况下,HashMap迭代器将抛出ConcurrentModificationException。 This is called 'fail-fast' behaviour of iterators as it is clearly mentioned in the java docs.
正如Java文档中明确提到的那样,这被称为迭代器的“快速失败”行为。 The best solution for you is to use ConcurrentHashMap.
最好的解决方案是使用ConcurrentHashMap。 If you don't want to use that one, then you have to do away with the multi-threading.
如果您不想使用该线程,则必须取消多线程。 As jim pointed out, if you can give more details about your multi-threading then you might get a better solution.
正如吉姆指出的那样,如果您可以提供有关多线程的更多详细信息,则可能会得到更好的解决方案。 Also, why do you want to NOT use ConcurrentHashMap?
另外,为什么不想使用ConcurrentHashMap? Any particular reason?
有什么特殊原因吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.