這是本文件的舊版!
CompletableFuture - Avoid transition task from one thread to another. It costs.
Problem
這問題通常發生在同時支援sync與async版本的API,或者是沒善用CompletableFuture功能的情況。以下是我的範例程式,基本上就是在透過CompletableFuture送出工作後,再等待執行結果以進行處理:
public Response doSmth(){ return doSmthAsync().join(); } public CompletableFuture<Response> doSmthAsync(){ return CompletableFuture.supplyAsync(()->{ return new Response(); }); } @Test public void transitionTask(){ Response reponse = doSmth(); System.out.println(reponse); }這程式的執行過程如下圖所示:
以單一工作來說,假如你的需求是屬於sync的情況,代表你必須等這個結果才能進行處理,那為何需要另外開一個thread pool來執行這個工作呢? 假如你的需求是要做成async的情況,那為何需要去等待結果去進行處理呢? 這兩者造成了client thread與使用的ExecutorServicec的浪費。
(本篇圖片都來自於link)
How to resolve?
Reference