For Java 6.0 you can download the package (jsr166y) from
For testing create the Java project "de.vogella.performance.forkjoin". If you are not using Java 7 you also need to "jsr166y.jar" to the classpath.
Create first a package "algorithm" and then the problem class.
package algorithm;
import java.util.Random;
/**
*
* This class defines a long list of integers which defines the problem we will
* later try to solve
*
*/
public class Problem {
private final int[] list = new int[2000000];
public Problem() {
Random generator = new Random(19580427);
for (int i = 0; i < list.length; i++) {
list[i] = generator.nextInt(500000);
}
}
public int[] getList() {
return list;
}
}
Define now the solver class. This class extends RecursiveTask.
Tip
The API defines other top classes, e.g. RecursiveAction, AsyncAction. Check the Javadoc for details.
package algorithm;
import java.util.Arrays;
import jsr166y.forkjoin.RecursiveAction;
public class Solver extends RecursiveAction {
private int[] list;
public long result;
public Solver(int[] array) {
this.list = array;
}
@Override
protected void compute() {
if (list.length == 1) {
result = list[0];
} else {
int midpoint = list.length / 2;
int[] l1 = Arrays.copyOfRange(list, 0, midpoint);
int[] l2 = Arrays.copyOfRange(list, midpoint, list.length);
Solver s1 = new Solver(l1);
Solver s2 = new Solver(l2);
forkJoin(s1, s2);
result = s1.result + s2.result;
}
}
}
Now define a small test class for testing it efficiency.
package testing;
import jsr166y.forkjoin.ForkJoinExecutor;
import jsr166y.forkjoin.ForkJoinPool;
import algorithm.Problem;
import algorithm.Solver;
public class Test {
public static void main(String[] args) {
Problem test = new Problem();
// Check the number of available processors
int nThreads = Runtime.getRuntime().availableProcessors();
System.out.println(nThreads);
Solver mfj = new Solver(test.getList());
ForkJoinExecutor pool = new ForkJoinPool(nThreads);
pool.invoke(mfj);
long result = mfj.getResult();
System.out.println("Done. Result: " + result);
long sum = 0;
// Check if the result was ok
for (int i = 0; i < test.getList().length; i++) {
sum += test.getList()[i];
}
System.out.println("Done. Result: " + sum);
}
}