How to benefit from Java 8's parallelStream?
-
21-12-2019 - |
Pergunta
I asked a question about dynamic filtering using Java 8 at [ How to dynamically do filtering in Java 8? ], Stuart Marks answered it wonderfully and gave some sample code to test with at : https://gist.github.com/stuart-marks/10076102.
Since I'm new to Java 8 and so I wonder if the following lines would make the program run faster on multi-core workstations with lots of data to process, at least theoretically :
// widgetList.stream().filter(compositePredicate).forEach(System.out::println);
widgetList.parallelStream().filter(compositePredicate).forEach(System.out::println);
// compositeCriteria.apply(widgetList.stream()).forEach(System.out::println);
compositeCriteria.apply(widgetList.parallelStream()).forEach(System.out::println);
Would relacing "widgetList.stream()" with "widgetList.parallelStream()" speedup the process ?
Solução
The best way would be to test it. However note that:
System.our.println
is a synchronized method, so the terminal operation is essentially sequential- only the filtering can therefore benefit from the parallelisation
- a parallel stream will probably be a gain for fairly large lists or for computationally intensive filtering operations
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow