Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Java RecursiveTask: split work only above a measured threshold

Last updated: 5 Oct 20265 min read
tutorial
AdvancedBy AITrove Editorial

RecursiveTask returns a value from a fork/join computation. A threshold keeps small ranges local so task scheduling does not cost more than the work being split.

Operational contract

This task sums a half-open range of shipment quantities. It splits only when the range exceeds 256 elements, forks one half, computes the other on the current worker, then joins the first. The caller owns the input array for the duration of computation; concurrent writes would break the result contract. Use long for the aggregate because many int quantities can overflow an int sum. The threshold is a workload choice, not a universal constant; measure it with representative array sizes and CPU budgets.

Failure case

An intake batch holds 47,000 unit counts. A task per element would create far more scheduling work than arithmetic. Chunking at 256 keeps each leaf useful while permitting multiple workers to take independent ranges. If the batch has only 82 entries, it stays sequential.

Java code

Java
import java.util.concurrent.RecursiveTask;

public class ShipmentQuantitySum extends RecursiveTask<Long> {
    private final int[] quantities;
    private final int start;
    private final int end;

    public ShipmentQuantitySum(int[] quantities, int start, int end) {
        this.quantities = quantities;
        this.start = start;
        this.end = end;
    }

    @Override protected Long compute() {
        if (end - start <= 256) {
            long total = 0;
            for (int index = start; index < end; index++) total += quantities[index];
            return total;
        }
        int middle = start + (end - start) / 2;
        ShipmentQuantitySum left = new ShipmentQuantitySum(quantities, start, middle);
        left.fork();
        long rightTotal = new ShipmentQuantitySum(quantities, middle, end).compute();
        return rightTotal + left.join();
    }
}

Performance and ownership cost

Total arithmetic work is O(N). Balanced splitting gives O(log N) critical-path depth for enough workers and about O(N/256) leaf tasks, though scheduling and memory traffic can dominate cheap sums. Task and stack storage grow with the split tree and active depth.

Common Mistakes

  • Do not fork a task for every small element.
  • Do not mutate the input while tasks are reading it.
  • Do not sum a large int array into an int without an overflow policy.

Connected lessons

java
fork/join task ownership
forkjoin-recursive-task-threshold
Storage details