Java Reference
In-Depth Information
Figure 7.2. iterate is inherently sequential.
This means that in this specific case the reduction process isn't proceeding as depicted in figure
7.1 : the whole list of numbers isn't available at the beginning of the reduction process, making it
impossible to efficiently partition the stream in chunks to be processed in parallel. By flagging
the stream as parallel, you're just adding to the sequential processing the overhead of allocating
each sum operation on a different thread.
This demonstrates how parallel programming can be tricky and sometimes counterintuitive.
When misused (for example, using an operation that's not parallel-friendly, like iterate) it can
actually worsen the overall performance of your programs, so it's mandatory to understand what
happens behind the scenes when you invoke that apparently magic parallel method.
Using more specialized methods
So how can you leverage your multicore processors and use the stream to perform a parallel sum
in an effective way? We discussed a method called LongStream.rangeClosed in chapter 5 . This
method has two benefits compared to iterate:
LongStream.rangeClosed works on primitive long numbers directly so there's no boxing and
unboxing overhead.
LongStream.rangeClosed produces ranges of numbers, which can be easily split into independent
chunks. For example, the range 1-20 can be split into 1-5, 6-10, 11-15, and 16-20.
Let's first see how it performs on a sequential stream to see if the overhead associated with
unboxing is relevant:
public static long rangedSum(long n) {
 
Search WWH ::




Custom Search