2017-06-21 322 views
4

使用Spring Async與僅僅自己返回CompletableFuture相比,有什麼優勢?直接使用Spring @Async和CompleteableFuture有什麼優勢?

+0

也許[THIS](https://stackoverflow.com/questions/533783/why-is-spawning-threads-in-java-ee-container-discouraged)會幫助你。 – Flown

+0

這可能在java 8之前就有意義了。但是CompletableFuture默認會派生到fork連接池中。 –

+3

你有一個託管環境。不建議自己產生線程,但如果必須的話,可以使用'CompletableFuture'和注入的'ExecutorService',它應該由容器管理。 – Flown

回答

5

您的應用程序由容器管理。由於不鼓勵你自己產生Thread,你可以讓容器注入一個託管的Executor

@Service 
class MyService { 
    @Autowired 
    private Executor executor; 

    public CompletableFuture<?> compute() { 
    return CompletableFuture.supplyAsync(() -> /* compute value */, executor); 
    } 
} 
2

沒有「」兩者之間:這是互補的技術:

  • CompletableFuture提供了一個方便的方法來異步計算的鏈的不同階段 - 比Spring的ListenableFuture更多的靈活性;
  • @Async爲您的後臺任務和線程提供了方便的管理,爲您的執行者提供了標準的Spring配置。

但是兩者都可以合併(since Spring 4.2)。假設你希望把下面的方法進入後臺任務返回CompletableFuture

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

你要做的:

  • 如果尚未:配置具有@EnableAsync您的應用程序和Executor
  • 註釋與@Async
  • 方法包裹它的結果到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"); 
} 

你可能注意到了,你不必理會提交後臺任務執行人:春負責的是你。您只需將結果包裝爲完整的CompletableFuture,以便籤名與呼叫者的期望相符。

相關問題