prerequisites:
1 - Overview
ForkJoinTaskis like a Callable combined with FutureRecursiveTask- has return type (likeCallable)RecursiveAction- has void return type (likeRunnable)
ForkJoinPoolis like ExecutorService that runsForkJoinTasks
2 - Code Example
to compute 42 + 32 + 22 + 12 = 30 we:
public class FactorialSquareCalculator extends RecursiveTask<Integer> {
private Integer n;
public FactorialSquareCalculator(Integer n) {
this.n = n;
}
@Override
protected Integer compute() {
if (n <= 1) {
return n;
}
FactorialSquareCalculator calculator = new FactorialSquareCalculator(n - 1);
calculator.fork();
return n * n + calculator.join();
}
}
next we create a ForkJoinPool to handle the execution:
ForkJoinPool forkJoinPool = new ForkJoinPool();
FactorialSquareCalculator calculator = new FactorialSquareCalculator(10);
forkJoinPool.execute(calculator);