[英]ConcurrentModificationException while iterating through HashMap
[英]HashMap ConcurrentModificationException while initializing with another HashMap
在多线程代码中,我在第3行看到ConcurrentModificationException
line 1: Map<String, String> attributMap = new HashMap<>();
line 2: if(attributeMap.size() > 0)
line 3: tagMyEvent(new HashMap<>(attributeMap));
java.util.ConcurrentModificationException
1 at java.util.HashMap$HashIterator.nextEntry(HashMap.java:851)
2 at java.util.HashMap$EntryIterator.next(HashMap.java:891)
3 at java.util.HashMap$EntryIterator.next(HashMap.java:890)
4 at java.util.HashMap.putAllForCreate(HashMap.java:485)
5 at java.util.HashMap.<init>(HashMap.java:257)
! 6 at tagMyEvent (test.java:line 3)
我能猜出此崩溃的唯一原因是:
为此将上面的代码更改,解决问题:
line 1: Map<String, String> attributMap = new HashMap<>();
line 2: if(attributeMap.size() > 0)
line 3: tagMyEvent(new ConcurrentHashMap<>(attributeMap));
要么
line 1: Map<String, String> attributMap = new ConcurrentHashMap<>();
line 2: if(attributeMap.size() > 0)
line 3: tagMyEvent(new ConcurrentHashMap<>(attributeMap));
如果不是,那么有人可以提出解决方案还是对导致此问题的确切原因有所了解。
提前致谢。
如果有的话,“ attributeMap”是需要并发的-因为如果它只是一个常规的HashMap,它仍然会拒绝在“新的ConcurrentHashMap”内部进行迭代,并且我们什么都没有实现……
话虽如此,我也建议
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.