Can a Java 8 `Stream` be parallel without you even asking for it?

前端 未结 5 1051
借酒劲吻你
借酒劲吻你 2021-01-01 15:35

As I see it, the obvious code, when using Java 8 Streams, whether they be \"object\" streams or primitive streams (that is, IntStream and friends)

5条回答
  •  误落风尘
    2021-01-01 16:05

    Well, answer to self...

    After thinking about it a little more seriously (go figure, such things only happen after I actually ask the question), I actually came up with a reason why...

    Intermediate operations may NOT be thread safe; as such, the API cannot make any assumptions, hence if the user wants a parallel stream, it has to explicitly ask for it and ensure that all intermediate operations used in the stream are thread safe.

    There is however the somewhat misleading case of Collectors; since a Collector cannot know by advance whether it will be called as a terminal operation on a stream which is parallel or not, the contract makes it clear that "just to be safe", any Collector must be thread safe.

提交回复
热议问题