Java Reference
In-Depth Information
public
public static
static
int
int
sequentialSumOfSquares
(
IntStream range
) {
return
return
range
.
map
(
x
->
x
*
x
)
.
sum
();
}
2. The code in
Example 6-11
multiplies every number in a list together and multiplies
the result by 5. This works fine sequentially, but has a bug when running in parallel.
Make the code run in parallel using streams and fix the bug.
Example 6-11. A buggy way of multiplying every number in a list together and mul-
tiplying the result by 5
public
public static
static
int
int
multiplyThrough
(
List
<
Integer
>
linkedListOfNumbers
) {
return
return
linkedListOfNumbers
.
stream
()
.
reduce
(
5
, (
acc
,
x
) ->
x
*
acc
);
}
3. The code in
Example 6-12
also calculates the sum of the squares of numbers in a list.
You should try to improve the performance of this code
without
degrading its quality.
I'm only looking for you to make a couple of simple changes.
Example 6-12. Slow implementation of summing the squares of numbers in a list
public
public
int
int
slowSumOfSquares
() {
return
return
linkedListOfNumbers
.
parallelStream
()
.
map
(
x
->
x
*
x
)
.
reduce
(
0
, (
acc
,
x
) ->
acc
+
x
);
}
NOTE
Make sure to run the benchmark code multiple times when timing. The sample
code provided on GitHub comes with a benchmark harness that you can use.