這是本文件的舊版!


Effective Java - Use caution when making streams parallel

在Java 8中,你只要用以下寫法,很容易就可以讓你的工作並行化:

list.stream().parallel() ..
list.parallelStream() ..
但這個item要強調的是: 千萬別亂用!!

Suitable Structure

能獲得較佳效能的結構有ArrayList、HashMap、HashSet、ConcurrentHashMap、arrays、int ranges與long ranges。這是由於它們的結構能夠容易被切割。

Suitable Operations

能獲得較佳效能的terminal operations包含reduce、min、max、count與sum;short-circuiting operations包含anyMatch、allMatch與noneMatch。(short-circuiting operations代表著滿足部分條件就可以停止繼續做下去,中文為短路操作,詳細範例可以參考link)

Unsuitable Operations

首先提到不適用的情況是使用Stream.iterate所產生的stream或者是透過limit處理的steam。這是由於預設的並行化流程並無法精準的知道該怎麼正確處理limit的邏輯。

Others

  1. collect則不適合用在parallel的情況中,因為組合集合開銷非常大。
  2. Prefer SplittableRandom than ThreadLocalRandom. (這個我還沒使用過,無法深入說明)

Conclusion

你要有理由或者測試去證明使用parallel會加快速度,否則代價就是性能災難或是功能直接出問題。

Effective Java第三版Item 48。

  • Effective Java, 3/e