Does the ordering of calls to sequential() and parallel() matter when processing a Java 8 stream pipeline?

Raffi Khatchadourian :

Does the placement of calls to sequential() and parallel() change how a Java 8 stream's pipeline is executed?

For example, suppose I have this code:

new ArrayList().stream().parallel().filter(...).count();

In this example, it's pretty clear that filter() will run in parallel. However, what if I have this code:

new ArrayList().stream().filter(...).parallel().count();

Does filter() still run in parallel or does it run sequentially? The reason it's not clear is because intermediate operations like filter() are lazy, i.e., they won't run until a terminal operation is invoked like count(). As such, by the time count() is invoked, we have a parallel stream pipeline but is filter() performed sequentially because it came before the call to parallel()?

Holger :

Note the end of the Stream’s class documentation:

Stream pipelines may execute either sequentially or in parallel. This execution mode is a property of the stream. 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.) This choice of execution mode may be modified by the BaseStream.sequential() or BaseStream.parallel() methods, and may be queried with the BaseStream.isParallel() method.

In other words, calling sequential() or parallel() only changes a property of the stream and its state at the point when the terminal operation is commenced determines the execution mode of the entire pipeline.

This might not be documented that clearly at all places, because, it wasn’t always so. In the early development there were prototypes having different mode for the stages. This mail from March 2013 explains the change.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=456181&siteId=1