I want to remove some objects from my collection:
public class Path {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToMany(mappedBy = "path", cascade = CascadeType.ALL, orphanRemoval = true)
List<Point> points;
public void removePoint(Point point) {
point.setPath(null);
this.getPoints().remove(point);
}
public class Point{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToMany(mappedBy = "point", cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true)
private List<PointOperation> operations;
@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "path_id", foreignKey = @ForeignKey(name = "FK_point_path"), nullable = false)
private Path path;
public void removePointOperation(PointOperation pointOperation) {
pointOperation.setPoint(null);
this.getOperations().remove(pointOperation);
}
When I want to delete all points with nested operations I get NPE error:
private void removeOldPoints(Window window) {
if (window.getPath().getPoints() != null) {
window.getPath().getPoints().forEach(s -> {
if (s.getOperations() != null && !s.getOperations().isEmpty()) {
s.getOperations().forEach(s::removePointOperation); // NPE here!
}
// Optional.ofNullable(s.getOperations()).ifPresent(s::removePointOperations);
window.getPath().removePoint(s);
});
}
}
Why? Because I remove items from collection that is in use? If yes how can I solve my problem?
stack trace:
java.util.ConcurrentModificationException: null
at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1043)
at java.base/java.util.ArrayList$Itr.next(ArrayList.java:997)
at org.hibernate.collection.internal.AbstractPersistentCollection$IteratorProxy.next(AbstractPersistentCollection.java:883)
at java.base/java.lang.Iterable.forEach(Iterable.java:74)
at pl.xxx.window.service.WindowPathService.lambda$removeOldPoints$0(WindowPathService.java:64)
at java.base/java.lang.Iterable.forEach(Iterable.java:75)
UPDATE
Unfortunately after implementing this solution with Iterator -> Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop
private void removeOldPoints(Window window) {
if (window.getPath().getPoints() != null) {
for (Iterator<Point> pointIterator = window.getPath().getPoints().iterator(); pointIterator.hasNext(); ) {
Point point = pointIterator.next();
if (point.getOperations() != null && !point.getOperations().isEmpty()) {
for (Iterator<PointOperation> operationIterator = point.getOperations().iterator(); operationIterator.hasNext(); ) {
PointOperation pointOperation = operationIterator.next();
point.removePointOperation(pointOperation);
operationIterator.remove();
}
}
window.getPath().removePoint(point);
pointIterator.remove();
}
}
}
I have java.util.ConcurrentModificationException: null in line:
operationIterator.remove();