Scrivio Interview library
CodingIntermediate7 min read · updated 12 November 2026

Write a RecursiveTask<Long> that sums a long[] array, and point out the common mistake in combining subtasks.

A RecursiveTask<Long> sums its range directly when the range is below a threshold such as 10,000 elements, and otherwise splits it in two, forks the left half, computes the right half on the current thread, and then joins the left: left.fork(); long r = right.compute(); long l = left.join(); return l + r;. The common mistakes are forking both halves and joining both, which wastes the current thread, and joining before computing, which waits for one half before starting the other and so serialises the work. For a plain sum, LongStream.of(array).parallel().sum() does all this for us.

Background to this question

Summing an array with fork/join is the hello world of parallel programming in Java, and it is a favourite coding question because a few lines reveal whether we understand how ForkJoinPool actually gets parallelism. The code compiles and gives the right answer even when it is written badly, so the mistakes only show up as a disappointing speed-up. In this answer, we will recap RecursiveTask, write the task step by step, look at the two common mistakes and why they hurt, choose a sensible threshold, and finish with the one-line alternative the JDK gives us.

1A Quick Recap of RecursiveTask

RecursiveTask<V> is an abstract class for fork/join tasks that return a result of type V. We extend it and implement one method, compute(), which either does the work directly or splits it into smaller RecursiveTasks. Two methods connect the tasks. fork() schedules a subtask to run asynchronously in the current ForkJoinPool, by pushing it onto the current worker's deque. join() returns the subtask's result, waiting for it if necessary, and while waiting, the worker can run other tasks instead of blocking.

We start the whole computation with pool.invoke(task), which runs the top task in the pool and returns its result.

2Writing the SumTask

Each task covers a range of the array, from start inclusive to end exclusive. If the range is small, it sums it in a loop. Otherwise it splits the range in the middle and creates two subtasks.

Java
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
class SumTask extends RecursiveTask<Long> {
static final int THRESHOLD = 10_000;
private final long[] a;
private final int start, end; // [start, end)
SumTask(long[] a, int start, int end) { this.a = a; this.start = start; this.end = end; }
@Override
protected Long compute() {
if (end - start <= THRESHOLD) { // small enough: sum it directly
long sum = 0;
for (int i = start; i < end; i++) sum += a[i];
return sum;
}
int mid = (start + end) >>> 1; // split in the middle
SumTask left = new SumTask(a, start, mid);
SumTask right = new SumTask(a, mid, end);
left.fork(); // left goes onto this worker's deque; a thief may take it
long r = right.compute(); // this thread works on the right half now
long l = left.join(); // runs left itself if still queued, or waits for the thief
return l + r;
}
}
long[] data = LongStream.rangeClosed(1, 10_000_000).toArray();
long total = ForkJoinPool.commonPool().invoke(new SumTask(data, 0, data.length));
System.out.println(total); // 50000005000000
Step throughWhat one call to compute() does
  1. Range of 10,000 elements or fewer?end - start <= THRESHOLD
    YesSum with a loop and returnNoSplit at mid
  2. left.fork()push left onto this worker's deque
  3. right.compute()this thread sums the right half, recursively
  4. left.join()run left here if still queued, or wait for the thief
  5. return l + rthe result goes to the parent task

5 steps in order. Play them, or step through them one at a time.

Notice the three lines at the end of compute(). We fork exactly one half, so it becomes available to idle workers. We call compute() on the other half directly, so the current thread does useful work at once, without the cost of queuing a task. Only then do we join the forked half. If nobody stole it, it is still on top of our deque and join() simply runs it on our thread; if a thief took it, it is often finished by the time we ask.

Also notice (start + end) >>> 1 for the middle. It cannot overflow, unlike (start + end) / 2 with very large indexes.

3Mistake 1: Forking Both and Joining Both

A very common version forks both halves and then joins both. It still gives the right answer, but it misuses the current thread.

Java
left.fork();
right.fork();
return left.join() + right.join(); // correct result, wasted thread time and extra queueing

The current thread has just done nothing but push two tasks; now it must get them back. Each fork and pop costs work, and the current thread no longer does a half of the work directly. Worse, the joins come in an awkward order: right is on top of the deque, so left.join() cannot just pop left, and the worker falls back on its slower join logic, searching its deque or helping with other tasks, while a perfectly good task sits on its own deque. Across thousands of tasks this adds overhead and can make the pool start compensating threads. If we really want to fork both, invokeAll(left, right) does it correctly, but fork one, compute the other is simpler.

4Mistake 2: Joining Before Computing

The second mistake puts the join before the compute.

Java
left.fork();
long l = left.join(); // waits for the left half first
long r = right.compute(); // only now starts the right half
return l + r; // correct result, but each level runs its halves one after the other
Three ways to combine the halves
CodeResultParallelism
left.fork(); right.compute(); left.join()correctgood: one half here, one available to thieves
left.fork(); right.fork(); join bothcorrectwasteful: thread queues both, then waits
left.fork(); left.join(); right.compute()correctpoor: halves run one after the other

Here the current thread asks for the left result immediately, so it ends up running the left half itself or waiting for it, and starts the right half only afterwards. At every level of the tree, the two halves run one after the other instead of side by side. The result is still correct, but the speed-up mostly disappears. The rule is: fork, then do your own work, then join.

5Choosing the Threshold

The threshold decides how small a task gets before we stop splitting. Every task has a fixed cost: creating the object, pushing and popping it, maybe a steal. Adding 10,000 longs takes a few microseconds, which is comfortably more than that overhead. With a threshold of 10, we would create about a million tasks for ten million elements and spend more time managing them than adding. With a threshold of 5 million, we would have only two leaf tasks and most cores would be idle.

A useful rule of thumb is to aim for somewhere between about 100 and 10,000 times as many leaf tasks as threads, and to make each leaf take at least tens of microseconds of work. Then measure with JMH, the Java benchmarking harness, because the right value depends on the work per element.

6The One-Line Alternative

For a simple sum, we do not need to write any of this. Parallel streams split arrays the same way and run on the common ForkJoinPool.

Java
long total = LongStream.of(data).parallel().sum(); // 50000005000000
long same = Arrays.stream(data).parallel().sum(); // the same, also splits the array efficiently

Writing the RecursiveTask is still worth knowing, because it is the model for custom divide-and-conquer work such as processing trees, merging sorted ranges or searching, where no ready-made stream operation exists.

7Follow-up questions

Why use >>> 1 instead of / 2 for the middle index?

Because start + end can overflow int when both are large, and the unsigned right shift treats the overflowed sum as an unsigned number, giving the correct middle. For arrays shorter than about a billion elements both forms work, but >>> 1 is the safe habit.

Should this run in the common pool or a dedicated ForkJoinPool?

For a short CPU-bound sum, the common pool is fine. In a server where the common pool is also used by parallel streams and async callbacks, a long-running computation is better placed in its own ForkJoinPool so it cannot delay unrelated work.

What changes if we use RecursiveAction instead?

RecursiveAction is the variant for tasks that return nothing, for example sorting an array in place. The structure is the same; compute() returns void and join() is used only to wait for completion.

8Conclusion

In this answer, we wrote a RecursiveTask<Long> that sums small ranges directly and splits larger ones, forking the left half, computing the right half on the current thread and then joining the left. We saw why forking and joining both halves wastes the current thread, why joining before computing serialises the work, how to pick a threshold large enough to cover task overhead, and that LongStream.of(array).parallel().sum() does the same for a plain sum.

What to say in the interviewAbout 100 seconds aloud

Open with

I would write a SumTask that extends RecursiveTask of Long and holds the array, a start and an end. In compute, if the range is at or below a threshold, say ten thousand elements, it sums them with a plain loop and returns.

Then, if they want more

Otherwise it finds the middle with an unsigned shift, creates a left and a right subtask, and then does three things in this order: left.fork, then long r equals right.compute, then long l equals left.join, and returns l plus r. The order is the point.

Forking the left half makes it available to idle workers, computing the right half directly keeps the current thread busy with real work, and joining last means that if nobody stole the left half, the thread just pops it from its own deque and runs it. The common mistakes still give the right answer, which is why they survive.

Forking both halves and joining both makes the current thread queue two tasks and then wait, and it joins in an awkward order for the deque. Joining the left before computing the right is worse, because each level then runs its halves one after the other, so the parallelism mostly disappears.

The threshold should make each leaf a few microseconds or more of work, so the overhead of creating and scheduling tasks stays small; I would tune it with JMH. And for a plain sum I would not write this at all: LongStream.of(array).parallel().sum() splits the array the same way on the common pool.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Write a RecursiveTask<Long> that sums a long[] array, and point out the common mistake...": https://scrivio-interview-library.netlify.app/java/executors/3d2749c481/