【问题标题】:HashMap ConcurrentModificationException while initializing with another HashMap使用另一个 HashMap 初始化时出现 HashMap ConcurrentModificationException
【发布时间】:2016-11-08 15:57:06
【问题描述】:

在多线程代码中,我在第 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)  

我能猜到这次崩溃的唯一原因是:

  • 在创建新的 HashMap(attributMap) 时正在修改 attributMap。

将上面的代码改成这个,解决问题:

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,它仍然会在“new ConcurrentHashMap”中被迭代,我们已经一无所获...

标签: java android hashmap concurrenthashmap concurrentmodification


【解决方案1】:

如果有的话,“attributeMap”是需要并发的——因为如果它只是一个普通的 HashMap,它仍然会拒绝在“new ConcurrentHashMap”中被迭代,我们什么也没做......

也就是说,我也很乐意建议

  1. 考虑 ConcurrentHashMap 是否真的足以满足您的需求,这取决于您在其上运行的其他操作,以及线程之间的协作级别,或者它们应该如何立即看到彼此的更改...
  2. 我假设我们只看到了部分代码 sn-p(显然您没有在方法中本地初始化“attributeMap”,因为这样就不会有并发问题)。所以也考虑测试其他问题 - 例如。如果完整的代码做了一些额外的操作,为了简单起见,这篇文章中省略了这些操作。请记住,即使您只有一个线程,某些操作也可能会产生 ConcurrentModificationException...

【讨论】:

  • 感谢@Pelit Mamani。我故意省略了另一段代码以保持简单。多个线程通过不同的方法将值添加到attributeMap。您是否建议即使在使用 ConcurrentHashMap 之后也可以看到 ConcurrentModificationException 而不管属性映射的修改方式如何?
  • 谢谢,当然我同意你的方法(它使阅读和理解变得容易)。只是想确定一下。谢谢:)
猜你喜欢
  • 2016-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-17
  • 1970-01-01
  • 1970-01-01
  • 2015-01-15
相关资源
最近更新 更多