prerequisites:

1 - Overview

  • ForkJoinTask is like a Callable combined with Future
    • RecursiveTask - has return type (like Callable)
    • RecursiveAction - has void return type (like Runnable)
  • ForkJoinPool is like ExecutorService that runs ForkJoinTasks

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);