差異處
這裏顯示兩個版本的差異處。
java:java:java8:concurrent:blockingoperationwithcompletablefuture:build_chain_before_execution [2019/01/13 22:41] tony [How to resolve?] |
java:java:java8:concurrent:blockingoperationwithcompletablefuture:build_chain_before_execution [2023/06/25 09:48] |
||
---|---|---|---|
行 1: | 行 1: | ||
- | {{tag>java concurrency}} | ||
- | ====== CompletableFuture - It may be useful to build chain of actions before execution. ====== | ||
- | ===== Problem ===== | ||
- | 下方這隻程式在Java8中應是相當常見: | ||
- | <code java> | ||
- | CompletableFuture.supplyAsync(()->{ | ||
- | dumpCurrentThreadName("supplyAsync"); | ||
- | return new Response(); | ||
- | }).whenComplete((response, ex)->{ | ||
- | dumpCurrentThreadName("whenComplete"); | ||
- | // process response | ||
- | }); | ||
- | </code> | ||
- | 它的問題是如果supplyAsync中的工作,在執行whenComplete前就結束了;當執行whenComplete時,有可能會使用client thread去執行工作而影響到工作接收的速度。以下是我的執行結果: | ||
- | <code> | ||
- | ForkJoinPool.commonPool-worker-3: supplyAsync | ||
- | main: whenComplete | ||
- | </code> | ||
- | 假如你的callback chain很長,遇到這個情況的機率就會越高。 | ||
- | ===== How to resolve? ===== | ||
- | 面對這個問題,在Java9中,允許你將實際的執行工作放到callback chain之後: | ||
- | <code java> | ||
- | CompletableFuture<Response> asyncJob = new CompletableFuture<>(); | ||
- | |||
- | asyncJob.whenComplete((response, ex)->{ | ||
- | dumpCurrentThreadName("whenComplete"); | ||
- | }); | ||
- | |||
- | asyncJob.completeAsync(()->{ | ||
- | dumpCurrentThreadName("supplyAsync"); | ||
- | return new Response(); | ||
- | }); | ||
- | </code> | ||
- | 輸出結果如下: | ||
- | <code> | ||
- | ForkJoinPool.commonPool-worker-3: supplyAsync | ||
- | ForkJoinPool.commonPool-worker-3: whenComplete | ||
- | </code> | ||
- | 這樣可以避免client thread跑去執行原本預期要async的工作,而增加了client thread的回應速度。\\ | ||
- | \\ | ||
- | 至於Java8就科科了。 | ||
- | ===== Reference ===== | ||
- | * [[https://qconsf.com/sf2017/system/files/presentation-slides/cf.pdf|Asynchronous API with | ||
- | CompletableFuture - Performance Tips and Tricks]] | ||
- | |||
- | ====== ====== | ||
- | ---- | ||
- | \\ | ||
- | ~~DISQUS~~ |