Java Reference
In-Depth Information
7.1. Parallel streams
In chapter 4 , we briefly mentioned that the Stream interface allows you to process its elements
in parallel in a very convenient way: it's possible to turn a collection into a parallel stream by
invoking the method parallelStream on the collection source. A parallel stream is a stream that
splits its elements into multiple chunks, processing each chunk with a different thread. Thus,
you can automatically partition the workload of a given operation on all the cores of your
multicore processor and keep all of them equally busy. Let's experiment with this idea by using a
simple example.
Let's suppose you need to write a method accepting a number n as argument and returning the
sum of all the numbers from 1 to the given argument. A straightforward (perhaps naïve)
approach is to generate an infinite stream of numbers, limiting it to the passed number, and
then reduce the resulting stream with a BinaryOperator that just sums two numbers, as follows:
In more traditional Java terms, this code is equivalent to its iterative counterpart:
public static long iterativeSum(long n) {
long result = 0;
for (long i = 1L; i <= n; i++) {
result += i;
}
return result;
}
This operation seems to be a good candidate to leverage parallelization, especially for large
values of n . But where do you start? Do you synchronize on the result variable? How many
threads do you use? Who does the generation of numbers? Who adds them up?
Don't worry about all of this. It's a much simpler problem to solve if you adopt parallel streams!
 
Search WWH ::




Custom Search