Java Reference
In-Depth Information
Other Parallel Array Operations
In addition to method
parallelSort
, class
Arrays
now contains methods
paral-
lelSetAll
and
parallelPrefix
, which perform the following tasks:
•
parallelSetAll
—Fills an array with values produced by a generator function
that receives an
int
and returns a value of type
int
,
long
or
double
. Depending
on which overload of method
parallelSetAll
is used, the generator function is
an object of a class that implements
IntToDoubleFunction
(for
double
arrays),
IntUnaryOperator
(for
int
arrays),
IntToLongFunction
(for
long
arrays) or
IntFunction
(for arrays of any non-primitive type).
•
parallelPrefix
—Applies a
BinaryOperator
to the current and previous array
elements and stores the result in the current element. For example, consider:
int
[] values = {
1
,
2
,
3
,
4
,
5
};
Arrays.parallelPrefix(values, (x, y) -> x + y);
This call to
parallelPrefix
uses a
BinaryOperator
that
adds
two values. After
the call completes, the array contains 1, 3, 6, 10 and 15. Similarly, the following
call to
parallelPrefix
, uses a
BinaryOperator
that
multiplies
two values. After
the call completes, the array contains 1, 2, 6, 24 and 120:
int
[] values = {
1
,
2
,
3
,
4
,
5
};
Arrays.parallelPrefix(values, (x, y) -> x * y);
In Chapter 17, you learned about Java SE 8 lambdas and streams. We mentioned that
streams are easy to
parallelize
, enabling programs to benefit from enhanced performance
on multi-core systems. Using the timing capabilities introduced in Section 23.12,
Fig. 23.29 demonstrates both
sequential
and
parallel
stream operations on a 10,000,000-
element array of random
long
values (created at line 17) to compare the performance.
1
// StreamStatisticsComparison.java
2
// Comparing performance of sequential and parallel stream operations.
3
import
java.time.Duration;
4
import
java.time.Instant;
5
import
java.util.Arrays;
6
import
java.util.LongSummaryStatistics;
7
import
java.util.stream.LongStream;
8
import
java.security.SecureRandom;
9
10
public class
StreamStatisticsComparison
11
{
12
public static void
main(String[] args)
13
{
14
SecureRandom random =
new
SecureRandom();
15
16
// create array of random long values
17
long
[] values = random.longs(
10_000_000
,
1
,
1001
).toArray();
Fig. 23.29
|
Comparing performance of sequential and parallel stream operations. (Part 1 of 3.)