Home > Blockchain >  ConcurrentModificationException when post a object
ConcurrentModificationException when post a object

Time:09-16

When I run a post for the first time (when the id is not yet saved in the database) it is returning "ConcurrentModificationException: null";

dto.getObservations().stream()
                .map(productObservationsService::convertDTOToModel)
                .forEach(model::addObservation);

and this is my entity:

@OneToMany(mappedBy = "relatedProduct", cascade = {CascadeType.PERSIST, CascadeType.MERGE})
private List<ProductObservationModel> observations;

public void addObservation(ProductObservationModel observationModel) {
    if (this.observations == null)
        this.observations = new ArrayList<>();

    observations.add(observationModel);
    observationModel.setRelatedProduct(this);
}

Does anyone know what can it be?

CodePudding user response:

To be completely honest i dont know what you mean with "When I run a post for the first time (when the id is not yet saved in the database)".

Your Problem is that you are trying to write to a List while iterating over it that was not made for that (observations).

If the list is always provided by you, you can change this.observations = new ArrayList<>() to this.observations = new CopyOnWriteArrayList<>(). You can read more on how the List works on the JavaDoc

If not you can copy the list before iterating or saving the added ProductObservationModel in a additional List and add them after iterating.

new ArrayList<>(dto.getObservations()).stream()
            .map(productObservationsService::convertDTOToModel)
            .forEach(model::addObservation);
  • Related