差異處
這裏顯示兩個版本的差異處。
Both sides previous revision 前次修改 下次修改 | 前次修改 | ||
java:java:java8:concurrent:blockingoperationwithcompletablefuture:avoid_transition_task [2019/01/13 15:00] tony [How to resolve?] |
java:java:java8:concurrent:blockingoperationwithcompletablefuture:avoid_transition_task [2023/06/25 09:48] (目前版本) |
||
---|---|---|---|
行 1: | 行 1: | ||
+ | {{tag>java concurrency}} | ||
====== CompletableFuture - Avoid transition task from one thread to another. It costs. ====== | ====== CompletableFuture - Avoid transition task from one thread to another. It costs. ====== | ||
===== Problem ===== | ===== Problem ===== | ||
行 15: | 行 16: | ||
@Test | @Test | ||
public void transitionTask(){ | public void transitionTask(){ | ||
- | Response reponse = doSmth(); | + | Response response = doSmth(); |
- | System.out.println(reponse); | + | System.out.println(response); |
} | } | ||
</code> | </code> | ||
行 24: | 行 25: | ||
(本篇圖片都來自於[[https://qconsf.com/sf2017/system/files/presentation-slides/cf.pdf|link]]) | (本篇圖片都來自於[[https://qconsf.com/sf2017/system/files/presentation-slides/cf.pdf|link]]) | ||
===== How to resolve? ===== | ===== How to resolve? ===== | ||
- | 針對sync的情況,其實你根本不需要額外透過ExecutorService去執行,client thread就可以幫你完成這個任務。如果是針對async的情況,這時候應該要好好善用CompletableFuture的callback功能才對。 | + | 針對sync的情況,其實你根本不需要額外透過ExecutorService去執行,client thread就可以幫你完成這個任務。如果是針對async的情況,這時候應該要好好善用CompletableFuture的callback功能才對: |
+ | <code java> | ||
+ | @Test | ||
+ | public void fixTransitionTask(){ | ||
+ | doSmthAsync() | ||
+ | .thenAccept(response->{ | ||
+ | System.out.println(response); | ||
+ | }); | ||
+ | } | ||
+ | </code> | ||
+ | 這樣你的client thread就可以回去做它該做的事情,避免在那等待而浪費。 | ||
===== Reference ===== | ===== Reference ===== | ||
* [[https://qconsf.com/sf2017/system/files/presentation-slides/cf.pdf|Asynchronous API with | * [[https://qconsf.com/sf2017/system/files/presentation-slides/cf.pdf|Asynchronous API with |