简体   繁体   中英

Java iterating collection throws ConcurrentModificationException after Save

Hi I am using hibernate for saving the objects to DB. I have a Parent object and set of child objects under it. While iterating over the child objects, if a specific criteria is matched then I publish an event using ApplicationEventPublisher, this event is handled separately, which adds few additional logics and saves the object. After the control returns from event handler, it throws "java.util.ConcurrentModificationException"

Below is the code,

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

There is a Event Listner,

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

But it throws java.util.ConcurrentModificationException at this point. Any idea how to rectify this? Any help is appreciated.

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)

You can iterate over a copy of the list like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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