本文介绍了为什么会抛出 ConcurrentModificationException 以及如何调试它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Collection(JPA 间接使用的 HashMap,它确实发生了),但显然代码随机抛出了 ConcurrentModificationException.是什么原因造成的,我该如何解决这个问题?通过使用一些同步,也许?

I am using a Collection (a HashMap used indirectly by the JPA, it so happens), but apparently randomly the code throws a ConcurrentModificationException. What is causing it and how do I fix this problem? By using some synchronization, perhaps?

这是完整的堆栈跟踪:

Exception in thread "pool-1-thread-1" java.util.ConcurrentModificationException
        at java.util.HashMap$HashIterator.nextEntry(Unknown Source)
        at java.util.HashMap$ValueIterator.next(Unknown Source)
        at org.hibernate.collection.AbstractPersistentCollection$IteratorProxy.next(AbstractPersistentCollection.java:555)
        at org.hibernate.engine.Cascade.cascadeCollectionElements(Cascade.java:296)
        at org.hibernate.engine.Cascade.cascadeCollection(Cascade.java:242)
        at org.hibernate.engine.Cascade.cascadeAssociation(Cascade.java:219)
        at org.hibernate.engine.Cascade.cascadeProperty(Cascade.java:169)
        at org.hibernate.engine.Cascade.cascade(Cascade.java:130)

推荐答案

这不是同步问题.如果正在迭代的基础集合被迭代器本身以外的任何东西修改,就会发生这种情况.

This is not a synchronization problem. This will occur if the underlying collection that is being iterated over is modified by anything other than the Iterator itself.

Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
    Entry item = it.next();
    map.remove(item.getKey());
}

当第二次调用 it.hasNext() 时,这将抛出一个 ConcurrentModificationException.

This will throw a ConcurrentModificationException when the it.hasNext() is called the second time.

正确的做法是

Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
    Entry item = it.next();
    it.remove();
}

假设这个迭代器支持remove()操作.

Assuming this iterator supports the remove() operation.

这篇关于为什么会抛出 ConcurrentModificationException 以及如何调试它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 16:37