1

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)???

Akin A
  • 9
  • 3
  • Does this answer your question? [What advantage is there to using Spring @Async vs. CompleteableFuture directly?](https://stackoverflow.com/questions/44685187/what-advantage-is-there-to-using-spring-async-vs-completeablefuture-directly) – pringi Feb 22 '22 at 09:33
  • Yes it gave me some more info, but im looking forward for something specifically on callableStatement – Akin A Feb 22 '22 at 16:21
  • https://www.baeldung.com/spring-data-java-8#completablefuture – isa_toltar Feb 28 '22 at 14:35

1 Answers1

0

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();
}
Ravi Gupta
  • 209
  • 1
  • 3