attish raj
attish raj

Reputation: 17

How should I use CompletableFuture for void method in springboot async

How should I use CompletableFuture for void method in springboot async. Explanation with examples will be appreciated

Upvotes: 0

Views: 2551

Answers (2)

Archimedes Trajano
Archimedes Trajano

Reputation: 41290

It may be easier to use the ThreadPoolTaskExecutor which is provided by Spring Boot with @EnableAsync and has the a similar signature to ExecutorService namely the submit method.

Example of use of it is

@Component
@lombok.RequiredArgsConstructor
public class MyComponent {
  private final ThreadPoolTaskExecutor taskExecutor;
  public void myMethod() throws Throwable {
    final Future<Void> future = taskExecutor.submit(
        () -> {
          ...
          return null;
        });
    
    try {
      ...
      future.get();
      ...
    } catch (ExecutionException e) {
      throw e.getCause();
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
    }
  }
}

Upvotes: 0

Simon Martinelli
Simon Martinelli

Reputation: 36133

Here is an example:

  @Async
  public CompletableFuture<Void> foo()  {
       // Do some work
       return CompletableFuture.completedFuture(null);
  }

Upvotes: 3

Related Questions