Execution Mode of a Stream – Streams
Execution Mode of a Stream
The two methods parallel() and sequential() are intermediate operations that can be used to set the execution mode of a stream—that is, whether it will execute sequentially or in parallel. Only the Collection.parallelStream() method creates a parallel stream from a collection, so the default mode of execution for most streams is sequential, unless the mode is specifically changed by calling the parallel() method. The execution mode of a stream can be switched between sequential and parallel execution at any point between stream creation and the terminal operation in the pipeline. However, it is the last call to any of these methods that determines the execution mode for the entire pipeline, regardless of how many times these methods are called in the pipeline.
The declaration statements below show examples of both sequential and parallel streams. No stream pipeline is executed, as no terminal operation is invoked on any of the streams. However, when a terminal operation is invoked on one of the streams, the stream will be executed in the mode indicated for the stream.
Stream<CD> seqStream1
= CD.cdList.stream().filter(CD::isPop); // Sequential
Stream<CD> seqStream2
= CD.cdList.stream().sequential().filter(CD::isPop); // Sequential
Stream<CD> seqStream3
= CD.cdList.stream().parallel().filter(CD::isPop).sequential(); // Sequential
Stream<CD> paraStream1
= CD.cdList.stream().parallel().filter(CD::isPop); // Parallel
Stream<CD> paraStream2
= CD.cdList.stream().filter(CD::isPop).parallel(); // Parallel
The isParallel() method can be used to determine the execution mode of a stream. For example, the call to the isParallel() method on seqStream3 below shows that this stream is a sequential stream. It is the call to the sequential() method that occurs last in the pipeline that determines the execution mode.
System.out.println(seqStream3.isParallel()); // false
Parallel streams are explored further in §16.9, p. 1009.
The following methods are inherited by the Stream<T> interface from its superinterface BaseStream. Analogous methods are also inherited by the IntStream, LongStream, and DoubleStream interfaces from the superinterface BaseStream.
Stream<T> parallel()
Stream<T> sequential()
Set the execution mode of a stream. They return a parallel or a sequential stream that has the same elements as this stream, respectively. Each method will return itself if this stream is already parallel or sequential, respectively.
These are intermediate operations that do not change the stream size, the stream element type, or the encounter order.
boolean isParallel()
Returns whether this stream would execute in parallel when the terminal operation is invoked. The method might yield unpredictable results if called after a terminal operation has been invoked.
It is not an intermediate operation.
Leave a Reply