Quick revision
The short answer
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.
What to remember
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.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
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.
- Range of 10,000 elements or fewer?end - start <= THRESHOLDYesSum with a loop and returnNoSplit at mid
- left.fork()push left onto this worker's deque
- right.compute()this thread sums the right half, recursively
- left.join()run left here if still queued, or wait for the thief
- 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.
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.
| Code | Result | Parallelism |
|---|---|---|
left.fork(); right.compute(); left.join() | correct | good: one half here, one available to thieves |
left.fork(); right.fork(); join both | correct | wasteful: thread queues both, then waits |
left.fork(); left.join(); right.compute() | correct | poor: 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.
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.
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.
- Official documentation
- java.util.concurrent, package documentation, JLS chapter 17, Threads and Locks
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/