Racing Subtasks in Java: anySuccessfulOrThrow and Hedged Requests
Use Joiner.anySuccessfulOrThrow to race equivalent subtasks: the first success wins, failures don't end the race, and the losers are cancelled. What happens when all fail or none were forked, and how to build a hedged request that asks a backup only when the primary is slow.
kvi5hnuCode Sprout team member6 min readOn this page
Some operations have several equivalent sources: exchange rates from three regional mirrors, a hotel's availability from two booking partners, a cached value and a fresh one. You don't need every answer, only the first good one. Joiner.anySuccessfulOrThrow() turns a scope into a race:
try (var scope = StructuredTaskScope.open(Joiner.<String>anySuccessfulOrThrow())) {
scope.fork(() -> ratesFrom("eu-west"));
scope.fork(() -> ratesFrom("ap-south"));
String rates = scope.join(); // the first subtask to succeed
}
The rules of the race
- The first subtask to complete successfully wins. Its result is what
join()returns, and the scope is cancelled at that moment, which interrupts every subtask still running. - A failure doesn't end the race. A mirror that fails quickly is simply out, and the others keep going.
- If every subtask fails,
join()throwsExecutionExceptionwith one of the failures as its cause. - If no subtask was forked,
join()throwsExecutionExceptionwith aNoSuchElementExceptioncause.
As with the other throwing joiners, an overload anySuccessfulOrThrow(Function<Throwable, X>) throws your own exception type instead (article 29).
Races and hedges in action
The program races three mirrors, shows the two failure cases, and then builds a hedged request. It uses the Java 27 preview API (java --enable-preview Racing.java on Java 27, no flag on Java 28).

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.StructuredTaskScope.Joiner;
public class Racing {
static final List<String> events = new CopyOnWriteArrayList<>();
static String mirror(String name, int ms, boolean fails) throws InterruptedException {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
events.add(name + " cancelled");
throw e;
}
if (fails) {
events.add(name + " failed");
throw new IllegalStateException(name + " returned 503");
}
events.add(name + " answered");
return "rates from " + name;
}
static long since(long start) { return Math.round((System.nanoTime() - start) / 1e6 / 100.0) * 100; }
/** Hedged request: ask the primary; only if it's slow, also ask the backup. */
static String hedged(int primaryMs, int hedgeAfterMs) throws InterruptedException, ExecutionException {
try (var scope = StructuredTaskScope.open(Joiner.<String>anySuccessfulOrThrow())) {
scope.fork(() -> mirror("primary", primaryMs, false));
scope.fork(() -> {
Thread.sleep(hedgeAfterMs); // wait before sending the duplicate request
return mirror("backup", 100, false);
});
return scope.join();
}
}
public static void main(String[] args) throws Exception {
// 1. Three mirrors race; the fastest success wins and the others are cancelled
long start = System.nanoTime();
String winner;
try (var scope = StructuredTaskScope.open(Joiner.<String>anySuccessfulOrThrow())) {
scope.fork(() -> mirror("eu-west", 300, false));
scope.fork(() -> mirror("us-east", 100, true)); // fastest, but fails
scope.fork(() -> mirror("ap-south", 200, false));
winner = scope.join();
} // close() waits for the cancelled loser
System.out.println("1. " + winner + " after " + since(start) + " ms; events: " + events);
// 2. Every mirror fails: join() throws, with one of the failures as the cause
events.clear();
try (var scope = StructuredTaskScope.open(Joiner.<String>anySuccessfulOrThrow())) {
scope.fork(() -> mirror("eu-west", 100, true));
scope.fork(() -> mirror("us-east", 200, true));
scope.join();
} catch (ExecutionException e) {
System.out.println("2. all failed: " + e.getCause().getClass().getSimpleName() + "; events: " + events);
}
// 3. No subtasks at all
try (var scope = StructuredTaskScope.open(Joiner.<String>anySuccessfulOrThrow())) {
scope.join();
} catch (ExecutionException e) {
System.out.println("3. nothing forked: " + e.getCause().getClass().getSimpleName());
}
// 4. Hedging: a fast primary never triggers the backup; a slow one does
events.clear();
start = System.nanoTime();
System.out.println("4a. " + hedged(100, 200) + " after " + since(start) + " ms; events: " + events);
events.clear();
start = System.nanoTime();
System.out.println("4b. " + hedged(1000, 200) + " after " + since(start) + " ms; events: " + events);
}
}
Output (times rounded to 100 ms):
1. rates from ap-south after 200 ms; events: [us-east failed, ap-south answered, eu-west cancelled]
2. all failed: IllegalStateException; events: [eu-west failed, us-east failed]
3. nothing forked: NoSuchElementException
4a. rates from primary after 100 ms; events: [primary answered]
4b. rates from backup after 300 ms; events: [backup answered, primary cancelled]
- The race.
us-eastwas fastest but failed at 100 ms. That didn't end anything:ap-southsucceeded at 200 ms and won, andeu-west, which needed 300 ms, was cancelled. The operation took 200 ms, the time of the fastest successful source. - All fail. Both mirrors failed, so
join()threwExecutionException. Its cause is one of the subtask failures, anIllegalStateExceptionhere. If you need all the failures, for example to log every mirror's error, useallUntiland inspect the handles instead. - Nothing forked. A race with no runners has no result, and
join()reports it as aNoSuchElementExceptioncause. This happens in real code when the list of sources is empty, so check for that before opening the scope or handle it explicitly.
Hedged requests
Racing every source on every call doubles or triples the load on them. A hedged request is a cheaper variant: send the request to the primary, and only if it hasn't answered within a short delay, send a duplicate to a backup. Whichever answers first wins. This cuts tail latency (the slow 1% of calls) at the cost of a few extra requests, and it's a well-known technique in large distributed systems.
With structured concurrency it's just a race in which one runner starts late:
scope.fork(() -> mirror("primary", primaryMs, false));
scope.fork(() -> {
Thread.sleep(hedgeAfterMs); // wait before sending the duplicate request
return mirror("backup", 100, false);
});
return scope.join();
- 4a. The primary answered at 100 ms, before the 200 ms hedge delay. It won, the scope was cancelled, and the hedge subtask was interrupted while still sleeping: the backup was never called.
- 4b. The primary was slow (1,000 ms). At 200 ms the hedge called the backup, which answered at 300 ms and won. The primary was cancelled. The call took 300 ms instead of 1,000.
Pick the hedge delay from your latency data, usually around the 95th percentile of the primary's response time. Then only the slowest few percent of calls send a second request.
When racing is safe
A race only makes sense when the subtasks are interchangeable and safe to abandon:
- Read-only calls are ideal: fetching rates, availability, a cached document.
- Writes are risky. Racing two "book this room" calls can book it twice: the loser may have done its work just before it was cancelled. Cancellation interrupts a thread, but it can't undo a request the remote service has already processed.
- Cancellation must work. Losers are cancelled by interruption. A loser stuck in a call that ignores interrupts keeps running, and the scope's
close()waits for it, so the race's latency gain disappears at the end of the block. Use clients with timeouts or interruptible I/O.
What's current
anySuccessfulOrThrow()is the Java 26+ name. In Java 25 the same joiner wasanySuccessfulResultOrThrow(), and failures surfaced asFailedException.- In Java 27 (JEP 533) and Java 28 (JEP 543, final),
join()throwsExecutionExceptionwhen all subtasks fail, andanySuccessfulOrThrow(Function)lets you choose the exception type. - The
ExecutorService.invokeAnymethod (article 21) offers a similar race for executors, but its losers belong to an executor rather than to a scope.
Common questions
How is this different from ExecutorService.invokeAny?
invokeAny also returns the first success and cancels the rest. But it returns before the cancelled tasks have actually stopped, and they run in an executor that outlives the call. A scope's close() waits until every loser has finished, so nothing from the race survives the block.
Which failure becomes the cause when every subtask fails?
One of them, and the API doesn't promise which. Don't depend on it. If you need every error, use Joiner.allUntil and read each Subtask.exception().
Can the winner be a subtask that returns null?
Yes. A null result is still a success. If null means "not found" in your code, throw instead so that the race continues with the other sources.
What if two subtasks succeed at almost the same moment? Only one wins: the first one the joiner sees. The other's result is ignored.
Summary
Joiner.anySuccessfulOrThrow()makesjoin()return the first successful result and cancel the rest.- Failures don't end the race. Only when all subtasks fail does
join()throwExecutionException. With no subtasks, the cause isNoSuchElementException. - A hedged request is a race in which the backup starts after a delay, cutting tail latency with few extra calls.
- Race only idempotent, interchangeable, interruptible operations: losers may already have done their work.
Practice questions
Three sources are raced: A fails at 50 ms, B succeeds at 400 ms, and C succeeds at 250 ms. What does join() return and when?
Answer
C's result, at about 250 ms. A's failure doesn't end the race. C is the first to succeed, so the scope is cancelled at that moment and B is interrupted.
A service races two payment providers with anySuccessfulOrThrow() to charge a customer. Why is that a bad idea?
Answer
Charging isn't idempotent. The losing provider may have processed the charge just before its subtask was cancelled, and cancellation only interrupts the local thread. It can't undo a remote operation. The customer could be charged twice. Races are for read-only or idempotent calls.
A hedged request uses a 200 ms hedge delay, but every call now hits both the primary and the backup. The primary's 95th-percentile latency is 600 ms. What's wrong, and what delay is more sensible?
Answer
The delay is shorter than the primary's typical response time, so most calls trigger the backup, which doubles the load. Set the delay near the primary's 95th percentile, around 600 ms, so only the slowest few percent of calls send a second request.
Previous: StructuredTaskScope Joiners in Java: Collecting Results, Waiting for All and allUntil
Next: Exception Handling in Structured Concurrency: ExecutionException, Causes and Custom Exceptions

More in Modern Java Concurrency
Quiz: Java Concurrency Changes From Java 21 to Java 28
Sixteen questions on what changed release by release: virtual threads final in 21, synchronized without pinning in 24, scoped values final in 25, and the long road of structured concurrency from subclasses to open() and Joiner, the Java 26 and 27 refinements, and final in 28.
Quiz: Java Concurrency's Delicate Details
Twenty edge cases of modern Java concurrency that surprise experienced developers: virtual thread priorities and names, semaphores without owners, null scoped values, cancelling a CompletableFuture, pool sizing with unbounded queues, and StructuredTaskScope's strict rules.
Quiz: Java Concurrency Interview Questions (Virtual Threads, Structured Concurrency, Scoped Values)
Twenty questions of the kind interviewers ask about modern Java concurrency: platform vs virtual threads, pinning, pools and limits, CompletableFuture, structured concurrency, scoped values vs ThreadLocal, reactive programming, and production diagnostics.
Quiz: Modern Java Concurrency Final Exam (All 7 Parts)
The final exam for the modern Java concurrency course: thirty questions across all seven parts, from platform threads, pools and CompletableFuture through virtual threads, the scheduler, structured concurrency, scoped values, reactive streams and frameworks.
Discussion
Sign in to ask a question or share what you learned.