Play for Scala + Hibernate 中的 ConcurrentModificationException

ConcurrentModificationException in Play for Scala + Hibernate

我在 Play/Scala、GroupItem 中有两个 Hibernate 类,其中一个组可能有很多项。我需要的是从一个组中删除所有项目。我尝试这样删除:

val group = session.get(classOf[Group],groupCode)
val it = group.items.iterator
while(it.hasNext) {
   val i = it.next
   group.items.remove(i)
}

第一次迭代工作正常,但在第二次迭代中我得到 ConcurrentModificationException

这是什么异常以及如何解决这个问题?

如果要从列表中删除当前正在迭代的元素,请使用

it.remove()

它从基础集合中删除此迭代器返回的最后一个元素。

如果您对直接修改列表时抛出 ConcurrentModificationException 的原因感兴趣,可以查看此 javadoc http://docs.oracle.com/javase/8/docs/api/java/util/ConcurrentModificationException.html

Note that this exception does not always indicate that an object has been concurrently modified by a different thread. If a single thread issues a sequence of method invocations that violates the contract of an object, the object may throw this exception. For example, if a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this exception.