繁体   English   中英

Java 迭代集合在保存后抛出 ConcurrentModificationException

[英]Java iterating collection throws ConcurrentModificationException after Save

嗨,我正在使用 hibernate 将对象保存到数据库。 我有一个父 object 和它下面的一组子对象。 在迭代子对象时,如果匹配特定条件,则我使用 ApplicationEventPublisher 发布事件,此事件将单独处理,这会添加一些额外的逻辑并保存 object。 控件从事件处理程序返回后,抛出"java.util.ConcurrentModificationException"

下面是代码,

  parent.getChild().forEach(child -> {
    if (child.getStatus().equals("PENDING")) {
        applicationEventPublisher.publishEvent(new NewEvent(child));
        publishLifeCycleEvent(deal);
      }
    }
  });

有一个事件监听器,

  @EventListener
  public void saveChildEvent(NewEvent childEvent) {
    Child child = childEvent.getChild();
    //...do processing
    childRepository.save(child);
  }

但此时它会抛出 java.util.ConcurrentModificationException 。 知道如何纠正这个问题吗? 任何帮助表示赞赏。

Stack Trace -
java.util.ConcurrentModificationException: null
    at java.base/java.util.HashMap$HashIterator.nextNode(HashMap.java:1493)
    at java.base/java.util.HashMap$KeyIterator.next(HashMap.java:1516)
    at org.hibernate.collection.internal.AbstractPersistentCollection$IteratorProxy.next(AbstractPersistentCollection.java:893)
    at java.base/java.lang.Iterable.forEach(Iterable.java:74)

您可以像这样遍历列表的副本:

var children = new ArrayList<>(parent.getChild());
children .forEach(child -> {
  if (child.getStatus().equals("PENDING")) {
    applicationEventPublisher.publishEvent(new NewEvent(child));
    publishLifeCycleEvent(deal);
  }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM