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

前端 未结 5 1052
借酒劲吻你
借酒劲吻你 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:08

    First, through the lens of specification. Whether a stream is parallel or sequential is part of a stream's state. Stream-creation methods should specify whether they create a sequential or parallel stream (and most in the JDK do), but they are not required to say so. If your stream source doesn't say, don't assume. If someone passes you a stream, don't assume.

    Parallel streams are allowed to fall back to sequential at their discretion (since a sequential implementation is a parallel implementation, just a potentially imperfect one); the opposite is not true.

    Now, through the lens of implementation. In the stream-creation methods in Collections and other JDK classes, we stick to a discipline of "create a sequential stream unless the user explicitly asks for parallelism". (Other libraries, however, make different choices. If they're polite, they'll specify their behavior.)

    The relationship between stream parallelism and Spliterator only goes in one direction. A Spliterator can refuse to split -- effectively denying any parallelism -- but it can't demand that a client split it. So an uncooperative Spliterator can undermine parallelism, but not determine it.

提交回复
热议问题