The compute method in Listing 2
implements the algorithm I described in
Listing 1. If the number of doubles to be
searched is less than a threshold (100),
then calculate the minimum; otherwise,
recurse on each half and wait for them
to join (complete). Once you have the
result of each half, calculate the minimum of those and return it.
The MinimumFinder class implements
the Recursive Task<Double> interface,
which is one of two interfaces defined
by the fork/join framework. The other
interface, RecursiveAction, is identical
except that its compute method doesn’t
return anything.
The magic is in the join() method. It
will wait for the subtasks to complete.
Figure 1 shows a simple benchmark of
the time it takes to search through 30
million random numbers using a single
core or the two cores on my laptop. I
calculated the average over 10 runs for a
single core, and then switched to doing
it again with two cores and repeated that
six times. By duplicating and averaging, I
can ensure that I get reliable results.
compute() {
if ( work.size < threshold ) {
} else {
f1 = fork(first half of work)
f2 = fork(second half of work)
wait for the forks to join
}
}
COMMUNITY
JAVA IN ACTION
ABOUT US
Figure 1
blog