问题描述
我不明白为什么当我遍历这个 multimap
时得到一个ConcurrentModificationException。
我阅读以下,但我不知道我是否理解了整个事情。
我试图添加一个同步块。但我的怀疑是什么同步,和什么时候。
I don't understand why I get a ConcurrentModificationException when I iterate through this multimap
.I read the following entry, but I am not sure if I understood the whole thing. I tried to add a synchronized block. But my doubt is what to synchronize with, and when.
multimap
是一个字段,创建方式如下:
The multimap
is a field and created like this :
private Multimap<GenericEvent, Command> eventMultiMap =
Multimaps.synchronizedMultimap(HashMultimap.<GenericEvent, Command> create());
并使用如下:
eventMultiMap.put(event, command);
并且这样(我试图在地图上同步这个部分,但没有成功)
and like this ( I tried to synchronize this part on the map, but without success )
for (Entry<GenericEvent, Command> entry : eventMultiMap.entries()) {
if (entry.getValue().equals(command)) {
eventMultiMap.remove(entry.getKey(), entry.getValue());
nbRemoved++;
}
}
推荐答案
删除一个集合,而你在迭代通过它将导致一个ConcurrentModificationException每次,即使它是在同一个线程中完成 - 正确的事情是获取一个显式迭代器,并调用.remove()。
Calling remove on a collection while you're iterating through it will cause a ConcurrentModificationException every time, even if it's all done in the same thread - the Right Thing to do is get an explicit iterator and call .remove() on that.
编辑:修改您的示例:
Iterator<Map.Entry<GenericEvent, Command>> i = eventMultiMap.entries().iterator();
while (i.hasNext()) {
if (i.next().getValue().equals(command)) {
i.remove();
nbRemoved++;
}
}
这篇关于Guava MultiMap和ConcurrentModificationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!