Multithreading: RecursiveAction performs a divide-and-conquer side effect

RecursiveAction is RecursiveTask's void-returning sibling, used when the recursive work fills in a shared structure instead of computing a value. invokeAll(left, right) forks both halves and waits for them, splitting the array-filling work across the pool.

Code
class FillTask extends RecursiveAction {
    private final int[] arr;
    private final int lo, hi;
    FillTask(int[] arr, int lo, int hi) { this.arr = arr; this.lo = lo; this.hi = hi; }
    protected void compute() {
        if (hi - lo <= 2) {
            for (int i = lo; i < hi; i++) arr[i] = i * i;
            return;
        }
        int mid = (lo + hi) / 2;
        FillTask left = new FillTask(arr, lo, mid);
        FillTask right = new FillTask(arr, mid, hi);
        invokeAll(left, right);
    }
}
int[] squares = new int[8];
ForkJoinPool pool = new ForkJoinPool(2);
pool.invoke(new FillTask(squares, 0, squares.length));
pool.shutdown();
System.out.println("Squares filled in place: " + Arrays.toString(squares));
Output
Squares filled in place: [0, 1, 4, 9, 16, 25, 36, 49]
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms