Reputation: 17
How should I use CompletableFuture for void method in springboot async. Explanation with examples will be appreciated
Upvotes: 0
Views: 2551
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
Reputation: 36133
Here is an example:
@Async
public CompletableFuture<Void> foo() {
// Do some work
return CompletableFuture.completedFuture(null);
}
Upvotes: 3