entModificationException和一个HashM

entModificationException和一个HashM

本文介绍了ConcurrentModificationException和一个HashMap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用JPA持久化对象。主对象与另一个对象具有所有的一对多关系。另一个对象存储在HashMap中。什么样的同步会解决这个问题?它似乎发生在完全随机的时间,是非常不可预测的。这里是我得到的异常:

I am persisting objects using JPA. The Main object has an owning One-Many relationship with another object. The other object is stored in a HashMap. What sort of synchronization would fix this problem? It seems to happen at completely random times and is very unpredictable. Here is the exception I get:

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 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和一个HashMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 14:16