What is the advantage of using Spring @Async vs. CompleteableFuture directly?

What is the advantage of using Spring Async versus just returning CompletableFuture own?

+5
source share
2 answers

Your application is managed by the container. Since you are not allowed to create Thread yourself, you can let the container enter a managed Executor .

 @Service class MyService { @Autowired private Executor executor; public CompletableFuture<?> compute() { return CompletableFuture.supplyAsync(() -> /* compute value */, executor); } } 
+5
source

No cons between them: these are additional technologies:

  • CompletableFuture provides a convenient way to connect the various stages of asynchronous computing - with more flexibility than Spring ListenableFuture ;
  • @Async provides convenient management of your background tasks and threads with the standard Spring configuration for your artist (s).

But both can be combined ( with Spring 4.2 ). Suppose you want to include the following method in a background job that returns CompletableFuture :

 public String compute() { // do something slow return "my result"; } 

What you need to do:

  • if not already done: configure the application using @EnableAsync and Executor bean
  • annotate method using @Async
  • completes its result in CompletableFuture.completedFuture()
 @Async public CompletableFuture<String> computeAsync() { // do something slow - no change to this part // note: no need to wrap your code in a lambda/method reference, // no need to bother about executor handling return CompletableFuture.completedFuture("my result"); } 

As you noticed, you don’t have to worry about sending the background task to the executor: Spring will take care of this for you. You only need to wrap the result in a completed CompletableFuture so that the signature matches the expected subscriber.

+2
source

Source: https://habr.com/ru/post/1269082/


All Articles