Search code examples
javaspringasynchronousjava-8completable-future

What advantage is there to using Spring @Async vs. CompleteableFuture directly?


What's the advantage of using Spring Async vs. Just returning the CompletableFuture on your own?


Solution

  • Your application is managed by the container. Since it's discouraged to spawn Threads on you own, you can let the container inject a managed Executor.

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