Parallel Streams - nus-cs2030/2122-s1 GitHub Wiki
parallel()
When To Use -
When the output of the stream does not depend on the order of the elements
-
When better performance is needed after considering the large overheading of Parallelizing
(FYI: NxQ rule of thumb to expect better performance with parallel: N(number of element) x Q(work per element) > 10k)
To Ensure Proper Execution of Parallel Stream
- Does not interfere with stream data like adding/deleting elements from the stream directly (same goes for sequential stream)
- Preferably Stateless (cf. sorted and limit which are stateful) with no side effects
- This is due to elements being completely processed at different times as shown below
jshell> Stream.of(10, 100, 1000).
...> parallel().
...> forEach(x -> System.out.println(x))
100
1000
10