Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
kvi5hnuCode Sprout team member10 min readOn this page
Real concurrent programs rarely run a single task. They split a job into many subtasks and combine the results: search every file, query several services, process each chunk of an array. Article 95 showed how to submit tasks one at a time. This article covers the tools for running groups of tasks. invokeAll waits for every result. invokeAny takes the first success. ExecutorCompletionService hands you results as they finish. Structured concurrency gives task groups a clear scope. And the fork-join framework handles recursive divide-and-conquer computations on all your cores.
invokeAll: wait for every task
invokeAll submits a collection of Callables, blocks until all of them have finished, and returns their futures in the same order as the tasks:
List<Callable<Long>> tasks = ...;
List<Future<Long>> results = executor.invokeAll(tasks);
for (Future<Long> result : results) {
if (result.state() == Future.State.SUCCESS)
process(result.resultNow());
else
handle(result.exceptionNow());
}
Because every future is already done, the Java 19 methods state(), resultNow() and exceptionNow() fit perfectly. No get() and no ExecutionException unwrapping. A typical use is counting how often a word occurs across many files: make one task per file, run them with invokeAll, and add up the counts. One bad file doesn't spoil the others, because its failure is just a FAILED future.
invokeAll(tasks, timeout, unit) returns when all tasks finish or the timeout expires. Tasks still running at that point are cancelled, so their futures report CANCELLED.
invokeAny: take the first success
invokeAny also submits a whole collection, but it returns the result of one task that completed successfully, normally the fastest, and cancels the rest. If every task fails, it throws an ExecutionException. The timed version throws TimeoutException.
It's the right tool for searches where any answer will do. Examples: find a file containing a word, find a factor of a large number by testing different ranges in parallel, or query redundant replicas and use whichever answers first. Writing the tasks for invokeAny takes a little care:
- Signal "not found" by throwing, not by returning
falseornull.invokeAnystops at the first task that returns, so a task that returns a "no luck" value would end the search. A failing task should throw, for exampleNoSuchElementException, so the search continues. - Respond to cancellation. Once one task wins, the others are interrupted. A search loop should check
Thread.currentThread().isInterrupted()and give up, or it will keep burning CPU for nothing.
Callable<Path> searchFor(String word, Path path) {
return () -> {
try (var in = new Scanner(path)) {
while (in.hasNext()) {
if (in.next().equals(word)) return path;
if (Thread.currentThread().isInterrupted()) return null; // cancelled
}
throw new NoSuchElementException(); // not here
}
};
}
Path found = executor.invokeAny(searchTasks);
ExecutorCompletionService: results as they arrive
invokeAll makes you wait for the slowest task before you see anything. To process results in the order they complete, wrap an executor in an ExecutorCompletionService. It submits tasks to the executor and puts each future into an internal blocking queue the moment it finishes:
var service = new ExecutorCompletionService<T>(executor);
for (Callable<T> task : tasks) service.submit(task);
for (int i = 0; i < tasks.size(); i++) {
Future<T> done = service.take(); // blocks until the next task completes
process(done.get());
}
poll() returns null immediately if nothing is ready yet, and poll(timeout, unit) waits for a limited time. In the demo, tasks submitted with delays of 600, 200 and 400 ms come back as 200, 400, 600.
Structured concurrency
invokeAll and invokeAny hint at a bigger idea. Structured programming replaced goto with blocks whose entry and exit are clear. Structured concurrency does the same for tasks. Subtasks are forked inside a scope, and when the scope's block ends, every subtask is guaranteed to be finished. If one fails, the others are cancelled automatically. If the parent is interrupted, so are its children. Thread dumps even show the parent–child structure.
Java's StructuredTaskScope API has been a preview feature since Java 21 (JEP 453 and its successors), and its shape changed between previews. It's still a preview in Java 26 (JEP 525) and Java 27 (JEP 533), which made only small changes, mostly to the Joiner interface. Since Java 25 (JEP 505), a scope is opened with a static factory, and a joiner defines the completion policy:
// preview API (Java 25): compile and run with --enable-preview
try (var scope = StructuredTaskScope.open()) { // default: fail if any subtask fails
Subtask<User> user = scope.fork(() -> findUser(id));
Subtask<List<Order>> orders = scope.fork(() -> fetchOrders(id));
scope.join(); // waits; throws if a subtask failed
return new Page(user.get(), orders.get());
} // all subtasks are complete or cancelled here
Other joiners, created by static factory methods of StructuredTaskScope.Joiner, give invokeAny-like behaviour (return the first successful result) or collect all results. The exact method names have changed between previews. Unlike invokeAll, the default policy cancels the remaining subtasks as soon as one fails. Until the API is final, check the documentation for your JDK version, and use invokeAll, invokeAny or CompletableFuture (article 102) in production code.
The fork-join framework
Some applications use huge numbers of mostly idle threads, like a server handling one connection per thread, and that's where virtual threads shine. Others want exactly one busy thread per core, splitting a CPU-heavy job such as image processing, sorting or numeric work across all of them. The fork-join framework is built for the second kind: problems that break down recursively.
if (problemSize < threshold)
solve problem directly
else {
break problem into subproblems
recursively solve each subproblem
combine the results
}
You express the computation as a subclass of RecursiveTask<T> if it produces a result, or RecursiveAction if it doesn't, and override compute. Here's how to count the elements of a big array that satisfy a predicate:
class Counter extends RecursiveTask<Integer> {
protected Integer compute() {
if (to - from < THRESHOLD) {
int count = 0;
for (int i = from; i < to; i++) if (filter.test(values[i])) count++;
return count;
}
int mid = from + (to - from) / 2;
var first = new Counter(values, from, mid, filter);
var second = new Counter(values, mid, to, filter);
invokeAll(first, second); // fork both halves and wait
return first.join() + second.join(); // combine
}
}
int count = new ForkJoinPool().invoke(new Counter(numbers, 0, numbers.length, x -> x > 0.5));
invokeAll(first, second) here is ForkJoinTask's own static method, not the executor method from above. It schedules both subtasks and waits for them. join() returns a finished task's result. There's also get(), but it throws checked exceptions that compute isn't allowed to throw, so join is the convenient choice. Another common pattern is first.fork(); int r2 = second.compute(); return first.join() + r2;, which computes one half in the current thread.

Work stealing
Behind the scenes, a ForkJoinPool balances the load with work stealing. Each worker thread has its own deque of tasks. A worker pushes the subtasks it creates onto the head of its own deque and pops them from there. Only the owner touches the head, so no locking is needed. When a worker runs out of work, it steals a task from the tail of another worker's deque. The tail holds the oldest and therefore largest subtasks, so one theft supplies plenty of work and thefts stay rare.
Practical notes
- Choose a sensible threshold. If subtasks are too small, the scheduling overhead dominates. If they're too large, cores sit idle. Thousands of elements per leaf is typical. Measure.
- Don't block inside fork-join tasks. The pool is tuned for pure computation, and blocking I/O or locks can starve it. The
ForkJoinPool.ManagedBlockerinterface exists for unavoidable blocking, but it's an advanced technique. Use an executor or virtual threads for I/O. - The common pool.
ForkJoinPool.commonPool()is a shared pool sized to the number of cores minus one. Parallel streams and manyCompletableFuturemethods use it by default.ForkJoinPoolisAutoCloseablesince Java 19, and closing the common pool has no effect. - In everyday code, parallel streams (
numbers.parallelStream().filter(…).count()) andArrays.parallelSortuse fork-join for you. WriteRecursiveTasks yourself when the problem has a custom recursive structure.
A complete example
The demo works on in-memory "files" so that it needs no disk access. It counts words with invokeAll, including one failing task, searches with invokeAny, shows a timed invokeAll cancelling a slow task, and collects results in completion order. Then it counts ten million random doubles with fork-join, checks the count against a sequential loop, and squares an array in place with a RecursiveAction.
import java.time.Duration;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.DoublePredicate;
public class Solution {
// in-memory "files" so the demo needs no disk access
static final Map<String, String> FILES = new TreeMap<>(Map.of(
"alpha.txt", "the cat sat on the mat",
"beta.txt", "a dog and a cat and a bird",
"gamma.txt", "the quick brown fox",
"delta.txt", "zebra crossing near the zoo"));
static long occurrences(String word, String file) {
return Arrays.stream(FILES.get(file).split(" ")).filter(word::equals).count();
}
// fork-join: count array elements matching a predicate by divide and conquer
static class Counter extends RecursiveTask<Integer> {
private static final long serialVersionUID = 1L;
static final int THRESHOLD = 1000;
private final double[] values;
private final int from, to;
private final transient DoublePredicate filter; // tasks are never serialized
Counter(double[] values, int from, int to, DoublePredicate filter) {
this.values = values; this.from = from; this.to = to; this.filter = filter;
}
@Override protected Integer compute() {
if (to - from < THRESHOLD) {
int count = 0;
for (int i = from; i < to; i++) if (filter.test(values[i])) count++;
return count;
}
int mid = from + (to - from) / 2;
var first = new Counter(values, from, mid, filter);
var second = new Counter(values, mid, to, filter);
invokeAll(first, second);
return first.join() + second.join();
}
}
// a RecursiveAction has no result: here it squares every element in place
static class Squarer extends RecursiveAction {
private static final long serialVersionUID = 1L;
private final long[] a;
private final int from, to;
Squarer(long[] a, int from, int to) { this.a = a; this.from = from; this.to = to; }
@Override protected void compute() {
if (to - from <= 10_000) {
for (int i = from; i < to; i++) a[i] *= a[i];
} else {
int mid = (from + to) >>> 1;
invokeAll(new Squarer(a, from, mid), new Squarer(a, mid, to));
}
}
}
public static void main(String[] args) throws Exception {
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
// 1. invokeAll: run every task, wait for all, results in submission order
var tasks = new ArrayList<Callable<Long>>();
for (String file : FILES.keySet()) tasks.add(() -> occurrences("the", file));
tasks.add(() -> occurrences("the", "missing.txt")); // will fail
List<Future<Long>> results = executor.invokeAll(tasks);
long total = 0;
for (Future<Long> result : results) {
if (result.state() == Future.State.SUCCESS) total += result.resultNow();
else System.out.println("one task failed: " + result.exceptionNow().getClass().getSimpleName());
}
System.out.println("occurrences of \"the\": " + total);
// 2. invokeAny: the first successful result wins, the rest are cancelled
var searches = new ArrayList<Callable<String>>();
for (String file : FILES.keySet())
searches.add(() -> {
for (String w : FILES.get(file).split(" ")) {
if (Thread.currentThread().isInterrupted()) return null; // cancelled: give up
if (w.equals("zebra")) return file;
}
throw new NoSuchElementException(); // a failure: keep looking elsewhere
});
System.out.println("\"zebra\" found in " + executor.invokeAny(searches));
try {
executor.invokeAny(List.<Callable<String>>of(() -> { throw new NoSuchElementException(); }));
} catch (ExecutionException e) {
System.out.println("no task succeeded -> ExecutionException");
}
// 3. invokeAll with a timeout cancels the stragglers
List<Future<String>> timed = executor.invokeAll(List.of(
() -> "fast",
() -> { Thread.sleep(Duration.ofSeconds(10)); return "slow"; }),
200, TimeUnit.MILLISECONDS);
System.out.println("with timeout: " + timed.get(0).state() + " " + timed.get(0).resultNow()
+ ", " + timed.get(1).state());
// 4. ExecutorCompletionService: results in completion order
var service = new ExecutorCompletionService<String>(executor);
int[] delays = {600, 200, 400};
for (int d : delays) service.submit(() -> { Thread.sleep(d); return d + " ms"; });
var order = new ArrayList<String>();
for (int i = 0; i < delays.length; i++) order.add(service.take().get());
System.out.println("completion order " + order);
}
// 5. fork-join: count values > 0.5 in ten million doubles
final int SIZE = 10_000_000;
var numbers = new double[SIZE];
var random = new Random(7);
for (int i = 0; i < SIZE; i++) numbers[i] = random.nextDouble();
int sequential = 0;
for (double x : numbers) if (x > 0.5) sequential++;
try (var pool = new ForkJoinPool()) {
int parallel = pool.invoke(new Counter(numbers, 0, SIZE, x -> x > 0.5));
System.out.println("fork-join count " + parallel + ", sequential count " + sequential);
}
// 6. RecursiveAction on the common pool
long[] squares = new long[100_000];
for (int i = 0; i < squares.length; i++) squares[i] = i;
ForkJoinPool.commonPool().invoke(new Squarer(squares, 0, squares.length));
System.out.println("squares[99999] = " + squares[99_999] + ", common pool parallelism > 0: "
+ (ForkJoinPool.commonPool().getParallelism() > 0));
}
}
one task failed: NullPointerException
occurrences of "the": 4
"zebra" found in delta.txt
no task succeeded -> ExecutionException
with timeout: SUCCESS fast, CANCELLED
completion order [200 ms, 400 ms, 600 ms]
fork-join count 5000388, sequential count 5000388
squares[99999] = 9999800001, common pool parallelism > 0: true
Common questions
What is the difference between invokeAll and invokeAny?
invokeAll waits for every task and returns all the futures, in the same order as the tasks. invokeAny returns the result of the first task that completes successfully and cancels the rest.
How do I process results as soon as each task finishes?
Use an ExecutorCompletionService. Submit the tasks through it, then call take() repeatedly. Each call returns the next finished future, in completion order.
Can I use structured concurrency in production code?
StructuredTaskScope is still a preview feature in Java 27, so it needs --enable-preview, and its API can change between releases. Many teams wait for the final version and use invokeAll or CompletableFuture in the meantime.
When should I write my own RecursiveTask instead of using a parallel stream?
When the problem has a recursive structure that streams don't express well, such as a custom divide-and-conquer algorithm over a tree or matrix. For filtering, mapping and summing over collections or arrays, a parallel stream is simpler and uses the same fork-join pool.
Why shouldn't I do I/O inside fork-join tasks? The fork-join pool has about one thread per core and expects tasks that compute. A task that blocks on I/O or a lock leaves a core idle, and many blocked tasks can stall the whole pool, including parallel streams that share the common pool. Run I/O on virtual threads or a separate executor.
API reference
java.util.concurrent.ExecutorService
| Method | Description |
|---|---|
<T> T invokeAny(Collection<? extends Callable<T>> tasks), plus a timeout version | runs the tasks and returns one successful result, cancelling the others; ExecutionException if none succeed |
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks), plus a timeout version | runs the tasks and returns all futures in task order once complete; on timeout, unfinished tasks are cancelled |
java.util.concurrent.ExecutorCompletionService<V>
| Method | Description |
|---|---|
ExecutorCompletionService(Executor e) | collects the results of tasks run by e |
Future<V> submit(Callable<V> task), submit(Runnable task, V result) | submits to the underlying executor |
Future<V> take() | removes the next completed future, waiting if needed |
Future<V> poll(), poll(long time, TimeUnit unit) | removes the next completed future, or returns null |
java.util.concurrent.ForkJoinPool, RecursiveTask<V>, RecursiveAction, ForkJoinTask<V>
| Method | Description |
|---|---|
ForkJoinPool(), ForkJoinPool(int parallelism) | pool with one worker per core, or the given parallelism |
static ForkJoinPool commonPool() | the shared pool used by parallel streams |
<T> T invoke(ForkJoinTask<T> task) | runs the task and returns its result |
protected abstract V compute() (RecursiveTask), protected abstract void compute() (RecursiveAction) | the recursive computation to override |
static void invokeAll(ForkJoinTask<?> t1, ForkJoinTask<?> t2), invokeAll(ForkJoinTask<?>... tasks) | forks the subtasks and waits for them |
ForkJoinTask<V> fork(), V join() | schedules asynchronously, and returns the result when done |
Summary
invokeAllruns a batch and returns all futures in order once everything is done. Usestate(),resultNow()andexceptionNow()to process them.invokeAnyreturns the first successful result and cancels the rest. Tasks should throw to signal "not found" and check for interruption.ExecutorCompletionServicedelivers futures in completion order.- Structured concurrency (preview) scopes subtasks to a block with automatic cancellation and cleanup.
- Fork-join splits CPU-bound work recursively with
RecursiveTaskorRecursiveAction, and balances it across cores by work stealing. Don't block in fork-join tasks.
Practice Questions
Why must an invokeAny search task throw an exception when it doesn't find anything, rather than return null?
invokeAny returns the result of the first task that completes normally. A task returning null would count as a success and end the search with null. Throwing marks the task as failed, so invokeAny keeps waiting for the others.
invokeAll returns. Can calling get() on one of the returned futures block?
No. invokeAll waits until every task is done (or cancelled, for the timed version), so get() returns or throws immediately. That's why resultNow() and exceptionNow() fit so well here.
You want to display search results as soon as each of 20 queries finishes. Which tool should you use?
An ExecutorCompletionService. Submit all 20 tasks, then call take() 20 times to get the futures in the order they complete.
Why does work stealing take tasks from the tail of another worker's deque?
The owner pushes and pops at the head without locking, so stealing at the other end minimizes contention. The tail also holds the oldest, largest subtasks, so one steal provides a lot of work and keeps steals infrequent.
A RecursiveTask makes HTTP calls in compute(). What's the problem?
Fork-join pools are sized for CPU-bound work. Blocking calls tie up their few worker threads and can starve the pool. Run I/O-bound work on virtual threads or a separate executor instead.
Previous: Java Callable, Future and ExecutorService: Thread Pools and Task Results
Next: Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Related reading
- Java Callable, Future and ExecutorService: Thread Pools and Task Results
- Java Virtual Threads, Interrupts and Daemon Threads: Thread Properties Explained
- Java Thread States: New, Runnable, Blocked, Waiting and Terminated
- Java Threads: Creating and Running Threads with Runnable and Thread
- Java Legacy Collections: Hashtable, Enumeration, Properties, Stack and BitSet

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java Callable, Future and ExecutorService: Thread Pools and Task Results
Run tasks that return results with Callable and Future, then let an ExecutorService manage threads: fixed, cached and single-thread pools, virtual-thread-per-task executors, get with timeouts, cancellation, Future.state and resultNow, closing executors, and throttling with semaphores.
Discussion
Sign in to ask a question or share what you learned.