How to Use Parallel Streams in Java
Streams in Java come in two basic flavors: sequential and parallel. Elements in a sequential stream are produced by the stream method and create streams that are processed one element after the next. Parallel streams, in contrast, can take full advantage of multicore processors by breaking its elements into two or more smaller streams, performing operations on them, and then recombining the separate streams to create the final result stream.
Each of the intermediate streams can be processed by a separate thread, which can improve performance for large streams.
By default, streams are sequential. But creating a parallel stream is easy: Just use the parallelStream method instead of the stream method at the beginning of the pipeline.
For example, to print all of HP’s spells using a parallel stream, use this code:
spells.parallelStream() .forEach(s -> System.out.println(s));
Note that when you use a parallel stream, you can’t predict the order in which each element of the stream is processed. That’s because when the stream is split and run on two or more threads, the order in which the processor executes the threads is not predictable.
To demonstrate this point, consider this simple example:
System.out.println("First Parallel stream: "); spells.parallelStream() .forEach(s -> System.out.println(s)); System.out.println("nSecond Parallel stream: "); spells.parallelStream() .forEach(s -> System.out.println(s));
When you execute this code, the results will look something like this:
First parallel stream: Fidelius Finite Incatatum Engorgio Locomotor Mortis Aparecium Avis Second parallel stream: Fidelius Engorgio Finite Incatatum Locomotor Mortis Avis Aparecium
Notice that although the same spells are printed for each of the streams, they are printed in a different order.