Java iterating collection throws ConcurrentModificationException after Save

Viewed 40

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 Listener:

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

But it throws java.util.ConcurrentModificationException at this point. How can I rectify this?

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)
1 Answers

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