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 :
for(Map.Entry<Integer, DealCountUpdater> e:new HashMap<Integer,DealCountUpdater>(dealCountMap).entrySet()){
I google this program,I know I can using a ConcurrentHashMap
开发者_如何学Python instead of a plain HashMap
,
but I want to know ,why I using :
new HashMap<Integer,DealCountUpdater>(dealCountMap)
to create new Instance for HashMap,still throw ConcurrentModificationException
?
how to fix it by not using ConcurrentHashMap
?
thanks for help :)
The reason is this:
- You create a new hashmap(H1) by passing another hashmap(H2) in its constructor.
- In the constructor fo H1, it tries to iterate through elements of H2, to add in itself.
- While the iteration in step 2 is going on, some other thread modifies H2. Hence ConcurrentModificationException.
How to solve it without using ConcurrentHashMap?
- Do external synchronization
- Use a copy-n-write map as described here.
But I would still suggest using ConcurrentHashMap, unless you really have your reasons.
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. This is called 'fail-fast' behaviour of iterators as it is clearly mentioned in the java docs. The best solution for you is to use 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? Any particular reason?
精彩评论