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

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

    The API doesn't have much to say on the matter:

    Streams are created with an initial choice of sequential or parallel execution. (For example, Collection.stream() creates a sequential stream, and Collection.parallelStream() creates a parallel one.)

    Regarding your line of reasoning that some intermediate operations may not be thread safe, you may want to read the package summary. The package summary discusses intermediate operations, stateful vs stateless, and how to properly use a Stream in some depth.

    Side-effects in behavioral parameters to stream operations are, in general, discouraged, as they can often lead to unwitting violations of the statelessness requirement, as well as other thread-safety hazards.

    Behavioral parameters being the arguments given to stateless intermediate operations.

    the API cannot make any assumptions

    The API can make any assumption it wishes. The onus is on the user of the API to meet those assumptions. However, assumptions may limit usability. The Stream API discourages the creation of a stateless intermediate operation that is not thread-safe. Since it is discouraged instead of prohibited, most Streams will be sequential "by default".

提交回复
热议问题