I have a Springboot API that makes a maximum of 6 Stored Procedure calls using the callable statement. I want to make this call asynchronous. Is it possible to achieve this using CompleteableFuture(java8)???
Database connections are typically not thread-safe. Are you planning to use one connection per call? If yes, following code will execute the callable statements in parallel. Please note I have used vavr library to simplify the exception handling.
public List<Boolean> concurrentCalls(Supplier<Connection> connectionSupplier, List<String> statements) {
Function<String, Either<Throwable, Boolean>> executeStatement = statement ->
Try.of(() -> connectionSupplier.get()
.prepareCall(statement)
.execute())
.toEither();
List<CompletableFuture<Boolean>> completableFutures = statements.stream()
.map(statement ->
CompletableFuture.supplyAsync(() -> executeStatement.apply(statement))
.thenApply( Either::get) // Handle exceptions as required
)
.collect(Collectors.toList());
return CompletableFuture.allOf( completableFutures.toArray( new CompletableFuture[0]))
.thenApply( any ->
completableFutures
.stream()
.map(CompletableFuture::join)
.collect(Collectors.toList())
)
.join();
}