I keep getting this error when I try to use multithreading (no problem if I run the program sequentially) in this service:
@Service
@RequiredArgsConstructor
public class Service {
private final Repository repository;
public List<A> getAs(String[] ids) {
List<A> as = Collections.synchronizedList(new ArrayList<>());
List<CompletableFuture<Boolean>> futures = new ArrayList<>();
for (String id : ids) {
futures.add(CompletableFuture.supplyAsync(() -> repository.findById(id).orElse(null)).thenApply(as::add));
}
futures.forEach(CompletableFuture::join);
return as;
}
}
Repository is a standard JpaRepository<A, String> and A:
public class A {
@Id
@Column(name = "id")
private String id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "b")
private B b;
}
The error is thrown when executing A#getB on any element of the returned list