我有一段简单的代码,它遍历一个映射表,在每个条目上检查一个条件,如果该条件为真,则执行该条目的方法。之后,该条目将从映射表中移除。
为了从映射表中删除一个条目,我使用了Iterator
来避免ConcurrentModificationException
异常。
但是我的代码确实在it.remove()
这行抛出了异常:
Caused by: java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.remove(Unknown Source) ~[?:1.8.0_161]
at package.Class.method(Class.java:34) ~[Class.class:?]
经过长时间的搜索,我找不到解决方法,所有答案都建议使用 Iterator.remove()
方法,但我已经在使用它了。 Map.entrySet()
的文档清楚地指出,可以使用 Iterator.remove()
方法从集合中删除元素。
非常感谢您的帮助。
我的代码:
Iterator<Entry<K, V>> it = map.entrySet().iterator();
while (it.hasNext()) {
Entry<K, V> en = it.next();
if (en.getValue().shouldRun()) {
EventQueue.invokeLater(()->updateSomeGui(en.getKey())); //the map is in no way modified in this method
en.getValue().run();
it.remove(); //line 34
}
}
en.getKey
。这肯定不是线程安全的。 - UninformedUserEventQueue.invokeLater
确实会这样做 - 就像我所说的那样。 - UninformedUseren.getKey()
不会改变 Map。 - EranEventQueue
这一行也没有帮助。 - superbadcodemonkey