Writing Custom Joiners in Java: Quorums, Collectors and Your Own Policies
Implement StructuredTaskScope.Joiner<T, R, R_X> for policies the built-ins don't cover: a quorum write that fails fast once success is impossible, a collector of every success and failure, and a best-offer joiner with a deadline. Which thread calls onFork, onComplete, result and timeout.
kvi5hnuCode Sprout team member8 min readOn this page
The built-in joiners (articles 29 and 30) cover all-or-nothing, first success and "collect until". Some operations need a different rule: a replicated write is done when three of five replicas acknowledge, a price search wants the cheapest offer within a deadline, a batch report wants every success and failure. For these you implement StructuredTaskScope.Joiner yourself.
The interface
In Java 27 and 28, a joiner has three type parameters and four methods:
public interface Joiner<T, R, R_X extends Throwable> {
default boolean onFork(Subtask<T> subtask) { ... } // a subtask is about to start
default boolean onComplete(Subtask<T> subtask) { ... } // a subtask finished
R result() throws R_X; // the outcome of join()
default R timeout() throws R_X { ... } // the outcome when the deadline expired
}
Tis the subtask result type,Rwhatjoin()returns, andR_Xthe exceptionjoin()throws. A joiner that never throws usesRuntimeException.onForkandonCompletereturn a boolean:truemeans cancel the scope now.result()is called once, byjoin(), after all subtasks have finished or the scope was cancelled. It returns the result or throwsR_X.timeout()is called instead ofresult()when the scope's deadline (article 32) expires. If it throws, the exception must have aCancelledByTimeoutExceptionas its cause. Override it whenever your joiner may be used with a timeout.
Who calls what

| Callback | Thread | When |
|---|---|---|
onFork | the owner, inside fork() | before the subtask's thread starts |
onComplete | the subtask's own thread | after it finishes with SUCCESS or FAILED, unless the scope is already cancelled |
result() / timeout() | the owner, inside join() | once, at the end |
Three consequences follow:
onCompleteruns concurrently. Several subtasks can finish at the same moment, so anythingonCompletewrites must be thread-safe: atomics, concurrent queues. A plainArrayListorintwould lose updates.onCompletenever seesUNAVAILABLE. It's only called for finished subtasks. Subtasks that finish after cancellation aren't reported at all, so a joiner can't count on seeing every subtask.- A joiner is single-use. Its state belongs to one scope. Create a new one for every
open.
onComplete should also be quick. It runs in the subtask's thread at the end of its work, and blocking there delays the decision to cancel.
Three custom joiners
The demo implements three policies. It uses the Java 27 preview API (java --enable-preview CustomJoiners.java on Java 27, no flag on Java 28).
import java.time.Duration;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.StructuredTaskScope.CancelledByTimeoutException;
import java.util.concurrent.StructuredTaskScope.Joiner;
import java.util.concurrent.StructuredTaskScope.Subtask;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
public class CustomJoiners {
// ---- 1. Quorum: succeed as soon as `needed` subtasks succeed; fail fast once that's impossible
static class QuorumFailed extends Exception {
private static final long serialVersionUID = 1L;
QuorumFailed(String message, Throwable cause) { super(message, cause); }
}
static final class QuorumJoiner<T> implements Joiner<T, List<T>, QuorumFailed> {
private final int needed, total;
private int forked; // only touched by the owner, in onFork
private final Queue<T> successes = new ConcurrentLinkedQueue<>();
private final AtomicInteger failures = new AtomicInteger();
private final AtomicReference<Throwable> firstFailure = new AtomicReference<>();
QuorumJoiner(int needed, int total) { this.needed = needed; this.total = total; }
@Override public boolean onFork(Subtask<T> subtask) { // runs in the owner thread
if (++forked > total) throw new IllegalStateException("more subtasks than the " + total + " declared");
return false; // never cancel at fork time
}
@Override public boolean onComplete(Subtask<T> subtask) { // runs in the subtask's thread
if (subtask.state() == Subtask.State.SUCCESS) {
successes.add(subtask.get());
return successes.size() >= needed; // quorum reached: cancel the rest
}
firstFailure.compareAndSet(null, subtask.exception());
return total - failures.incrementAndGet() < needed; // too many failures: quorum impossible
}
@Override public List<T> result() throws QuorumFailed {
List<T> got = List.copyOf(successes);
if (got.size() >= needed) return got.subList(0, needed);
throw new QuorumFailed("only " + got.size() + " of " + needed + " acknowledgements", firstFailure.get());
}
@Override public List<T> timeout() throws QuorumFailed {
throw new QuorumFailed("quorum not reached in time", new CancelledByTimeoutException());
}
}
// ---- 2. Collect everything: successes and failures, never cancel, partial report on timeout
record Report<T>(List<T> successes, List<String> failures, boolean complete) {}
static final class CollectingJoiner<T> implements Joiner<T, Report<T>, RuntimeException> {
private final Queue<T> successes = new ConcurrentLinkedQueue<>();
private final Queue<String> failures = new ConcurrentLinkedQueue<>();
@Override public boolean onComplete(Subtask<T> subtask) {
// Only finished subtasks reach onComplete: the state is SUCCESS or FAILED, never UNAVAILABLE
if (subtask.state() == Subtask.State.SUCCESS) successes.add(subtask.get());
else failures.add(subtask.exception().getMessage());
return false;
}
@Override public Report<T> result() { return new Report<>(new ArrayList<>(successes), new ArrayList<>(failures), true); }
@Override public Report<T> timeout() { return new Report<>(new ArrayList<>(successes), new ArrayList<>(failures), false); }
}
// ---- 3. Best offer: the cheapest result; on timeout, the cheapest seen so far
static final class CheapestJoiner<T> implements Joiner<T, Optional<T>, RuntimeException> {
private final Comparator<? super T> order;
private final AtomicReference<T> best = new AtomicReference<>();
CheapestJoiner(Comparator<? super T> order) { this.order = order; }
@Override public boolean onComplete(Subtask<T> subtask) {
if (subtask.state() == Subtask.State.SUCCESS) {
T offer = subtask.get();
best.accumulateAndGet(offer, (a, b) -> a == null || order.compare(b, a) < 0 ? b : a);
}
return false;
}
@Override public Optional<T> result() { return Optional.ofNullable(best.get()); }
@Override public Optional<T> timeout() { return Optional.ofNullable(best.get()); }
}
// ---- simulated services
static String writeReplica(int replica, int ms, boolean fails) throws InterruptedException {
Thread.sleep(ms);
if (fails) throw new IllegalStateException("replica " + replica + " unreachable");
return "r" + replica;
}
record Offer(String partner, int price) {}
static Offer offer(String partner, int ms, int price) throws InterruptedException {
Thread.sleep(ms);
if (price < 0) throw new IllegalStateException(partner + " returned an error");
return new Offer(partner, price);
}
static long since(long start) { return (System.nanoTime() - start) / 100_000_000 * 100; } // whole 100 ms
public static void main(String[] args) throws Exception {
// 1a. Five replicas, quorum of 3: done when the third acknowledgement arrives
long start = System.nanoTime();
try (var scope = StructuredTaskScope.open(new QuorumJoiner<String>(3, 5))) {
scope.fork(() -> writeReplica(1, 100, false));
scope.fork(() -> writeReplica(2, 200, true));
scope.fork(() -> writeReplica(3, 300, false));
scope.fork(() -> writeReplica(4, 400, false));
scope.fork(() -> writeReplica(5, 900, false));
System.out.println("1a. acknowledged by " + scope.join() + " after " + since(start) + " ms");
}
// 1b. Three replicas fail early: 5 - 3 < 3, so the quorum is impossible and the scope stops
start = System.nanoTime();
try (var scope = StructuredTaskScope.open(new QuorumJoiner<String>(3, 5))) {
scope.fork(() -> writeReplica(1, 100, true));
scope.fork(() -> writeReplica(2, 200, true));
scope.fork(() -> writeReplica(3, 300, true));
scope.fork(() -> writeReplica(4, 900, false));
scope.fork(() -> writeReplica(5, 900, false));
scope.join();
} catch (QuorumFailed e) {
System.out.println("1b. after " + since(start) + " ms: " + e.getMessage() + "; first cause: " + e.getCause().getMessage());
}
// 2. A report of everything, with a deadline
try (var scope = StructuredTaskScope.open(new CollectingJoiner<String>(),
cf -> cf.withTimeout(Duration.ofMillis(350)))) {
scope.fork(() -> writeReplica(1, 100, false));
scope.fork(() -> writeReplica(2, 200, true));
scope.fork(() -> writeReplica(3, 300, false));
scope.fork(() -> writeReplica(4, 1000, false));
System.out.println("2. " + scope.join());
}
// 3. Cheapest hotel offer within 350 ms
try (var scope = StructuredTaskScope.open(new CheapestJoiner<Offer>(Comparator.comparingInt(Offer::price)),
cf -> cf.withTimeout(Duration.ofMillis(350)))) {
scope.fork(() -> offer("Partner A", 100, 129));
scope.fork(() -> offer("Partner B", 200, 117));
scope.fork(() -> offer("Partner C", 300, -1));
scope.fork(() -> offer("Partner D", 1000, 99)); // cheapest, but too slow
System.out.println("3. best offer in time: " + scope.join().orElseThrow());
}
}
}
Output (times in whole 100 ms):
1a. acknowledged by [r1, r3, r4] after 400 ms
1b. after 300 ms: only 0 of 3 acknowledgements; first cause: replica 1 unreachable
2. Report[successes=[r1, r3], failures=[replica 2 unreachable], complete=false]
3. best offer in time: Offer[partner=Partner B, price=117]
The quorum joiner
A replicated store writes to five replicas and treats the write as durable once three acknowledge. Waiting for all five would make every write as slow as the slowest replica, and failing on the first error would make one bad replica fail every write.
onCompleteadds each success to a concurrent queue and cancels as soon as three have succeeded (1a: replicas 1, 3 and 4 by 400 ms; replica 5's 900 ms write was cancelled, and replica 2's failure didn't matter).- It also counts failures and cancels as soon as the quorum has become impossible: with five replicas, three failures leave at most two possible successes (1b: stopped at 300 ms instead of waiting for the two slow replicas).
result()returns the first three acknowledgements, or throwsQuorumFailedwith the first failure as the cause. BecauseR_XisQuorumFailed,join()is declared to throw exactly that type.timeout()throwsQuorumFailedwith aCancelledByTimeoutExceptioncause, as the contract requires.
The joiner takes the total number of replicas in its constructor. Computing "impossible" from the number forked so far would be a race: a subtask that fails very quickly can complete while the owner is still forking, and the joiner would wrongly conclude that the quorum can't be reached. onFork, which runs in the owner, now only checks that no more subtasks are forked than declared. Since only the owner touches forked, it needs no synchronization.
Remember what cancellation means for writes: a cancelled replica write may still have reached the replica. Quorum systems handle that at the protocol level, with version numbers and read repair. The joiner only decides when the caller may stop waiting.
The collecting joiner
CollectingJoiner never cancels. It records every success and every failure message, and result() returns a Report. Its timeout() returns the same report with complete = false, so with a 350 ms deadline (part 2) the caller got the two successes and one failure that happened in time, and knew the report was partial.
The comment in onComplete records an API fact: UNAVAILABLE can't happen there, so a plain if/else on SUCCESS is enough. Code that treats UNAVAILABLE in onComplete as "cancelled" has a branch that never runs. Cancelled subtasks simply aren't reported.
Compared with allUntil(s -> false), a collecting joiner produces exactly the result type you want (a report, a map, a summary) instead of a list of handles to inspect afterwards.
The best-offer joiner
CheapestJoiner keeps the best result seen so far in an AtomicReference, updated with accumulateAndGet so concurrent completions can't overwrite each other. With a 350 ms deadline (part 3), partner D's cheaper offer arrived too late, partner C failed, and the joiner returned partner B's offer, the cheapest that arrived in time. Both result() and timeout() return an Optional, which is empty if no partner answered.
Other policy ideas
- Enough results: cancel after the first N successes, such as five hotel offers for a results page.
- Failure budget: cancel when more than 20% of subtasks have failed, after a minimum sample.
- Stop on a fatal error: cancel on an
AuthenticationException, but tolerate transient errors. - Prefer a primary: return the primary's result if it succeeds, otherwise the first backup's.
Some ideas don't belong in a joiner. Limiting how many subtasks run at once isn't a completion policy. A semaphore acquired inside each subtask (article 12) does it more simply than blocking in onFork, which would stall the owner.
What's current
Joiner<T, R, R_X>withtimeout()is the Java 27 (JEP 533) API, final in Java 28 (JEP 543).- In Java 25 and 26,
Joinerhad two type parameters (Joiner<T, R>),result()was declaredthrows Throwable, andjoin()wrapped whatever it threw inFailedException. In Java 25 the callbacks tookSubtask<? extends T>, and Java 26 added avoid onTimeout()hook. Porting a custom joiner to Java 27 means addingR_X, narrowingresult()'sthrowsclause, and implementingtimeout()instead ofonTimeout().
Common questions
When should I write a custom joiner instead of using allUntil?
When you want join() to return a specific result type, or when the decision needs state, such as counts, a best-so-far value or a quorum. allUntil is enough for simple stop conditions when you don't mind inspecting handles afterwards.
Can onComplete call subtask.get()?
Yes. The "join first" rule from article 27 only restricts the owner thread, and onComplete runs in the subtask's thread after its outcome is set.
What happens if onComplete throws?
The exception isn't delivered to join(). It goes to the subtask thread's uncaught-exception handler. Keep onComplete simple, and record problems in the joiner's state instead.
Can a joiner return null?
Yes, if R allows it, as the default joiner does with Void. An Optional, as in CheapestJoiner, is usually clearer for "maybe no result".
Summary
- A custom joiner implements
Joiner<T, R, R_X>:onForkandonCompletedecide when to cancel, andresult()andtimeout()produce the outcome ofjoin(). onFork,result()andtimeout()run in the owner.onCompleteruns concurrently in subtask threads, so its state must be thread-safe.onCompleteis only called forSUCCESSandFAILEDsubtasks, and not after cancellation.- A quorum joiner cancels once enough subtasks succeed or success becomes impossible. A collecting joiner reports everything. A best-offer joiner returns the best result within a deadline.
- If
timeout()throws, the exception's cause must be aCancelledByTimeoutException. Use a new joiner for every scope.
Practice questions
A joiner stores successes in an ArrayList from onComplete. Tests pass, but in production some results go missing. Why?
Answer
onComplete runs in each subtask's own thread, often concurrently. Unsynchronized ArrayList.add calls from several threads can lose elements or corrupt the list. Use a ConcurrentLinkedQueue, a synchronized collection, or atomics.
A quorum joiner decides "impossible" with forkedSoFar - failures < needed. What can go wrong if the first subtask fails within microseconds?
Answer
onComplete can run while the owner is still forking. With one subtask forked and one failure, 1 - 1 < 3 is true, so the joiner cancels the scope before the other subtasks have even started. Give the joiner the total number of subtasks up front, or only decide impossibility after all forks.
A custom joiner's timeout() throws new QuorumFailed("too slow", null). What's wrong with it?
Answer
The Joiner contract requires an exception thrown from timeout() to have a CancelledByTimeoutException as its cause, so callers can tell timeouts from other failures. It should be new QuorumFailed("too slow", new CancelledByTimeoutException()).
Previous: Configuring StructuredTaskScope in Java: Names, Thread Factories and Timeouts
Next: Memory Visibility in Structured Concurrency: What fork() and join() Guarantee

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.