Calling sequential on parallel stream makes all previous operations sequential Calling sequential on parallel stream makes all previous operations sequential multithreading multithreading

Calling sequential on parallel stream makes all previous operations sequential


Switching the stream from parallel() to sequential() worked in the initial Stream API design, but caused many problems and finally the implementation was changed, so it just turns the parallel flag on and off for the whole pipeline. The current documentation is indeed vague, but it was improved in Java-9:

The stream pipeline is executed sequentially or in parallel depending on the mode of the stream on which the terminal operation is invoked. The sequential or parallel mode of a stream can be determined with the BaseStream.isParallel() method, and the stream's mode can be modified with the BaseStream.sequential() and BaseStream.parallel() operations. The most recent sequential or parallel mode setting applies to the execution of the entire stream pipeline.

As for your problem, you can collect everything into intermediate List and start new sequential pipeline:

new Random().ints(100).boxed()        .parallel()        .map(this::slowOperation)        .collect(Collectors.toList())        // Start new stream here        .stream()        .map(Function.identity())//some fast operation, but must be in single thread        .collect(Collectors.toSet());


In the current implementation a Stream is either all parallel or all sequential. While the Javadoc isn't explicit about this and it could change in the future it does say this is possible.

S parallel()

Returns an equivalent stream that is parallel. May return itself, either because the stream was already parallel, or because the underlying stream state was modified to be parallel.

If you need the function to be single threaded, I suggest you use a Lock or synchronized block/method.