Parallel processing
We have seen that changing from a sequential stream to a parallel stream can lead to incorrect results if the code was not written and tested for processing a parallel stream. The following are a few more considerations related to the parallel stream.
Stateless and stateful operations
There are stateless operations, such as filter()
, map()
, and flatMap()
, which do not keep data around (do not maintain state) while moving from processing from one stream element to the next. And there are stateful operations, such as distinct()
, limit()
, sorted()
, reduce()
, and collect()
, which may pass the state from previously processed elements to the processing of the next element.
Stateless operations usually do not pose a problem when switching from a sequential stream to a parallel one. Each element is processed independently and the stream can be broken into any number of sub-streams for independent processing.
With stateful operations, the situation is different. To start with,using...