为什么会引发ConcurrentModificationException以及如何对其进行调试 [英] Why is a ConcurrentModificationException thrown and how to debug it

查看:117
本文介绍了为什么会引发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)


推荐答案

这不是同步问题。如果要迭代的基础集合被Iterator本身以外的其他东西修改,则会发生这种情况。

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());
}

这将引发 ConcurrentModificationException 当第二次调用 it.hasNext()时。

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以及如何对其进行调试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆