Skip to main content
Executors and thread pools · Topic 7 of 7

Fork/Join pool

Definition​

The Fork/Join pool splits a big task into smaller ones (fork), runs them in parallel, and combines the results (join). Idle threads steal work from busy ones. Parallel streams use it behind the scenes.

Example code​

Summing a large array by splitting it

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

class SumTask extends RecursiveTask<Long> {
private final int[] numbers;
private final int from, to;

SumTask(int[] numbers, int from, int to) { this.numbers = numbers; this.from = from; this.to = to; }

@Override
protected Long compute() {
if (to - from <= 10_000) { // small enough: just add them
long sum = 0;
for (int i = from; i < to; i++) sum += numbers[i];
return sum;
}
int middle = (from + to) / 2;
SumTask left = new SumTask(numbers, from, middle);
SumTask right = new SumTask(numbers, middle, to);
left.fork(); // run the left half in parallel
return right.compute() + left.join(); // do the right half here, then combine
}
}

class Demo {
public static void main(String[] args) {
int[] numbers = new int[1_000_000];
java.util.Arrays.fill(numbers, 1);

long total = ForkJoinPool.commonPool().invoke(new SumTask(numbers, 0, numbers.length));
System.out.println(total);
}
}

// Output:
// 1000000

Finished this page? Track your progress (saved only in your browser).