Parallel Array
Explore how to utilize ParallelArray with lambdas and streams in Java 8 to perform parallel data processing. Understand the improvements over previous Java versions and simplify concurrent operations using parallel streams.
We'll cover the following...
A little history
The ParallelArray was part of JSR-166 but ended up being excluded from the standard Java library.
It exists and was released to the public domain. You can download it from the JSR website.
Parallel array in Java
Although it was already out there, it wasn’t easy to use until closures were included in the
Java language. In Java 7, using the ParallelArray looks like the following:
public class Student {
String name;
int graduationYear;
double gpa;
}
// this predicate
final Ops.Predicate < Student > isSenior =
new Ops.Predicate < > () {
public boolean op(Student s) {
return s.graduationYear == Student.THIS_YEAR;
}
};
// and this conversion operation
final Ops.ObjectToDouble < Student > selectGpa =
new Ops.ObjectToDouble < > () {
public double op(Student student) {
return student.gpa;
}
};
// create a fork-join-pool
ForkJoinPool fjPool = new ForkJoinPool();
ParallelArray < Student > students = new ParallelArray < > (fjPool, data);
// find the best GPA:
double bestGpa = students.withFilter(isSenior)
.withMapping(selectGpa)
.max();
In Java 8, we can do the following:
// create a fork-join-pool
ForkJoinPool pool = new ForkJoinPool();
ParallelArray < Student > students = new ParallelArray < > (pool, data);
// find the best GPA:
double bestGpa = students
.withFilter((Student s) - > (s.graduationYear == THIS_YEAR))
.withMapping((Student s) - > s.gpa)
.max();
However, Java 8’s addition of stream() and parallelStream() makes this even easier:
double bestGpa = students
.parallelStream()
.filter(s - > (s.graduationYear == THIS_YEAR))
.mapToDouble(s - > s.gpa)
.max().getAsDouble();
This makes it extremely simple to switch between a sequential implementation and a concurrent one.