這是本文件的舊版!


Blocking Operation of CompletableFuture

這陣子在研究CompletableFuture時,剛好看到一篇Oracle關於CompletableFuture如何使用才能有好效能的投影片。我在這裡做了些整理,分享給大家;如果有理解有問題或不足的地方,希望大家可以幫忙更正或補充。本篇圖片都來自於Reference中的投影片。本篇說到五個重點:

  • Avoid transition task from one thread to another. It costs.
  • Avoid blocking inside CompletableFuture chains. It costs.
  • Carefully avoid transition task from one thread to another. It costs.
  • It may be useful to build chain of actions before execution.
  • Different ThreadPools show different performance.

前四點我會分別說明。第五點如字面上所說,ThreadPool本來就要根據需求而去使用,這裡我不特別探討。

如下圖所示,使用ThreadPool最害怕的就是遇到Blocking的操作,這將會降低整個ThreadPool的生產力。

面對這問題,作者建議針對Blocking操作可以在發送後,透過Aux Thread執行;中間透過completableFuture的compose串接;Aux Thread執行完畢後,會將結果丟給串接的completableFuture,並讓工作繼續回到原本的ThreadPool執行。如下圖所示: