Run an agent's tool calls in parallel on Java 25 virtual threads, with a per-call timeout, a step deadline, cancellation and a concurrency limit, in a lab.
What you'll learn: how to run the tool calls of one model reply at the same time on Java 25 virtual threads, return the results in the order the model asked, and keep one slow or broken tool from taking the whole agent down.
It is 02:50 in the Parcelo incident (invented company, invented night). The model has just asked for three things: the alert text, a database metric and the deploy log. Your loop runs them one after another. Each call goes over the network and each one waits. Nothing about the second call depends on the first, so your program sits idle while it could be asking all three questions at once.
The fix is small to write and easy to get wrong. This lesson builds it in plain Java, a parallel executor of about 100 lines, and tests the parts that go wrong: a tool that fails, a tool that never returns, a step that runs out of time, and an API that only allows two calls at once. The single idea: fan out, join in order, and give every wait an end.
Everything in this lesson runs against the model script from the agent loop lesson, so the output is the same every time. A real model decides for itself how many tools to ask for in one reply, and may ask for one at a time. The lab proves the plumbing around the model, not how a live model uses it.
The idea in one picture
Figure 1. One model reply, three virtual threads, one ordered join
How to read this: follow the moving packets. The three calls leave the executor at the same moment and are waited for together; the results rejoin in the order the model asked for them, whichever call finished first.
Why an agent spends its time waiting
A tool call is almost never computation. It asks a monitoring system for a metric, queries a ticket database, fetches a page, calls a model. The thread that makes the call sits blocked until the answer arrives. A program like that is I/O bound: its speed is set by how long it waits, not by how fast it computes.
Waiting adds up when it happens in a row, and overlaps when it happens together. If three calls take 2, 3 and 1 time units, running them in a row costs 6 and running them at once costs 3, the time of the slowest. Those numbers are made up to show the arithmetic; the shape is the point.
Figure 2. Waiting in a row or waiting together (illustrative units)
flowchart LR
accTitle: Sequential waiting adds up, parallel waiting takes the longest
accDescr: With three calls of 2, 3 and 1 time units, the sequential loop waits 6 units in total. The parallel loop starts all three together and waits 3 units, the time of the slowest call.
subgraph SEQ["Sequential loop: total = 2 + 3 + 1"]
direction LR
S1["get_alert: 2"] --> S2["query_metric: 3"] --> S3["search_logs: 1"] --> SE["wait 6"]
end
subgraph PAR["Parallel loop: total = the longest"]
direction LR
P0["model reply"] --> P1["get_alert: 2"]
P0 --> P2["query_metric: 3"]
P0 --> P3["search_logs: 1"]
P1 --> PE["wait 3"]
P2 --> PE
P3 --> PE
end
How to read this: the top row is a queue, each call waits for the one before. In the bottom group the three calls share the same waiting time.
TIP
Picture it: you need three quotes from three suppliers. You can phone the first, wait on hold, hang up, then phone the second. Or you can ask three colleagues to phone one supplier each and report back. The colleagues do not make any supplier answer faster; they only stop you waiting in a line. The analogy stops where the colleagues cost salary: a thread costs memory, which is why the next section matters.
The agent loop also waits on the model itself, and that wait is not parallel: the next model call needs the results of this step. Parallel tool calls shorten one step, not the number of steps.
What virtual threads change
Without virtual threads, one blocked thread means one blocked operating-system thread, so people kept the thread count small with pools and rewrote blocking code as callbacks. A virtual thread is a Thread that the Java runtime schedules for you and that is cheap enough to create for every task. When it blocks, the platform thread under it can run another virtual thread.
The virtual threads lesson explains the model, shows a lab that counts blocked tasks, and covers pinning (a blocked virtual thread that cannot step off its carrier thread) and the JDK Flight Recorder event that reports it. This lesson does not repeat it. It uses one idea from it: one virtual thread per task, never a pool of virtual threads.
For an agent that means one virtual thread per tool call, created when the model's reply arrives and gone when the call returns.
Figure 3. A waiting call costs a virtual thread, not an operating-system thread
How to read this: the packet to the cloud is a request that takes a while. While it is away the virtual thread holds no carrier, so the carriers stay free for any virtual thread that has work.
It is an ordinary ExecutorService, so the code that submits work looks like any thread-pool code. What changes is that there is no pool size to tune.
Fan out, then join in the order of the calls
The executor does four things for one model reply:
Starts every call on its own virtual thread and gets a Future for each.
Waits for the futures, but never past the step's deadline.
Cancels whatever has not finished when the wait ends.
Returns one result per call, in the order of the calls, each carrying the call's id.
Order matters because the model matches results to requests by id and reads them as a list. If results arrived in finishing order, a test that passes on a quiet laptop would reorder on a busy server. The lab has a test that forces the opposite order (the last call finishes first) and still expects the results in call order.
Figure 4. What the executor does, message by message
sequenceDiagram
accTitle: Parallel executor fan-out and ordered join
accDescr: The agent loop gives the executor three calls a, b and c. The executor starts one virtual thread for each. Call c finishes first, then a, then b. The executor puts the results back in the order a, b, c and returns them to the loop.
participant L as Agent loop
participant X as Executor
participant A as Thread for a
participant B as Thread for b
participant C as Thread for c
L->>X: execute calls a, b, c
X->>A: start
X->>B: start
X->>C: start
Note over A,C: all three run at the same time
C-->>X: result c, first to finish
A-->>X: result a
B-->>X: result b
X->>X: sort results back into call order
X-->>L: results a, b, c
How to read this: arrows to the three threads leave together, arrows back arrive in any order, and the executor restores the order before the loop sees anything.
Build it. This is the whole execute method. The finally block is the cancellation rule: whatever happens above, every future that is not finished gets cancelled.
public List<Message.ToolResult> execute(List<ToolCall> calls) {
longdeadline= System.nanoTime() + config.stepDeadline().toNanos();
List<Future<Message.ToolResult>> futures = calls.stream().map(call -> threads.submit(() -> runOne(call))).toList();
try {
for (Future<Message.ToolResult> future : futures) {
future.get(Math.max(0, deadline - System.nanoTime()), TimeUnit.NANOSECONDS);
}
} catch (TimeoutException spent) {
// the step's budget is spent: fall through and cancel whatever has not finished
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
} catch (ExecutionException e) {
thrownewIllegalStateException("a tool task died with an Error", e.getCause());
} finally {
futures.forEach(future -> future.cancel(true));
}
return IntStream.range(0, calls.size())
.mapToObj(i -> futures.get(i).isCancelled() ? cancelled(calls.get(i)) : futures.get(i).resultNow())
.toList();
}
Walk through it. deadline is one moment in time, computed once. Each future.get waits for the time that is left, not a fresh allowance, so three slow calls cannot add three timeouts together. Waiting in call order is fine even when call 3 finishes first: its result is simply already there when the loop reaches it.
When the deadline passes, get throws TimeoutException, the finally cancels everything unfinished, and the final stream builds the answer: a cancelled future becomes an error result, a finished one gives its result. A call that finished before the deadline keeps its result.
TIP
Picture it: a waiter takes orders from table 4, 7 and 9 and the kitchen finishes table 9 first. She still puts the plates in front of each table, not in front of whoever is nearest. The ticket number (the call id) is what makes that possible. The analogy stops at the kitchen: here every plate is cooked by a different cook at the same time.
Failures stay inside their own call
If one tool throws, the others must still finish and the model must still get an answer for every call. The rule is the same as in the sequential loop of the agent loop lesson: every failure becomes an error result the model can read. An unknown tool, bad arguments, an exception, a timeout and a cancellation all use the same shape, a ToolResult with error = true and a sentence that says what happened.
runOne runs inside a call's own virtual thread. Unknown tools and invalid arguments are refused before anything runs and before a permit is taken. The permit is released in a finally, so a failing tool cannot leak it; the lab has a test that uses a single permit and a failing tool to prove it.
TIP
Picture it: a fuse box. When the kettle shorts, one fuse trips and the lights stay on. Each tool call has its own fuse, the error result. Where the analogy stops: a fuse protects the house from the kettle, but nothing here protects the model from a wrong answer. A tool that returns a plausible wrong value is not caught by any of this.
Timeouts and deadlines are two different clocks
These two words get mixed up, and the difference decides what the agent does when something is slow.
A timeout limits one call. It starts when the tool starts running.
A deadline limits the whole step. It starts when the calls are submitted and includes any time spent waiting for a permit.
Figure 5. Two clocks, one step
How to read this: the shaded zone is what the deadline covers. The red dashed path is what the call timeout does, and it starts only at the box "Tool runs".
The lab implements the call timeout with a watchdog: a second virtual thread that sleeps for the timeout and then interrupts the worker.
private Message.ToolResult runWithTimeout(Tool tool, ToolCall call) {
AtomicBooleantimedOut=newAtomicBoolean();
Threadworker= Thread.currentThread();
Threadwatchdog= Thread.ofVirtual().start(() -> {
try {
Thread.sleep(config.callTimeout());
timedOut.set(true);
worker.interrupt();
} catch (InterruptedException toolFinishedFirst) {
// nothing to do: the tool returned before the timeout
}
});
try {
returnnewMessage.ToolResult(call.id(), call.name(), tool.execute(call.arguments()), false);
} catch (Exception e) {
if (timedOut.get()) {
return error(call, "timed out after " + config.callTimeout().toMillis() + " ms");
}
if (e instanceof InterruptedException) {
return cancelled(call);
}
return error(call, "the tool failed: " + e.getMessage());
} finally {
watchdog.interrupt();
}
}
A sleeping virtual thread costs almost nothing, which is why a watchdog per call is affordable. When the tool returns first, the finally interrupts the watchdog and it ends quietly. When the watchdog wakes first, it sets a flag and interrupts the worker; the tool's blocking call throws InterruptedException, and the flag tells the code to report a timeout rather than a cancellation.
NOTE
On call, 3 a.m.: Dana runs the night shift at Marlow Freight. Her agent asks a tracking service for a parcel's position, and one night the service accepts the connection and never answers. Her first code had a 30-second timeout per call and no deadline for the step. Three calls to the stuck service cost 90 seconds before the model heard anything. She switched to parallel calls with a 5-second step deadline, and the model learned within 5 seconds that tracking was down. Invented example.
Cancellation is a request, not a command
When a call times out or the step's deadline passes, the executor calls future.cancel(true). The true means "interrupt the thread if it is running". An interrupt sets a flag on the thread; blocking methods such as Thread.sleep and CountDownLatch.await notice it and throw InterruptedException. Code that never blocks and never checks the flag does not notice at all.
Figure 6. The states of one tool call
stateDiagram-v2
accTitle: States of one parallel tool call
accDescr: A call is submitted, waits for a permit, then runs. From running it can finish with a result, fail with an exception, or time out. While it is submitted, waiting or running, the step deadline can cancel it. Every ending becomes a result the model can read.
[*] --> Submitted
Submitted --> WaitingForPermit
WaitingForPermit --> Running: permit acquired
Running --> Done: returns
Running --> Failed: throws
Running --> TimedOut: call timeout
Submitted --> Cancelled: step deadline
WaitingForPermit --> Cancelled: step deadline
Running --> Cancelled: step deadline
Done --> [*]
Failed --> [*]
TimedOut --> [*]
Cancelled --> [*]
How to read this: every path ends in a box that turns into an error or a normal result. There is no state where the model is left without an answer for a call.
So cancellation depends on the tool. A tool that blocks in a way that responds to an interrupt stops at once. A tool that catches InterruptedException and carries on does not, and Java cannot force it to stop. The lab does not hide this: the executor stops waiting for such a tool and the step still returns on time, but the tool keeps running in the background. That is why close() uses shutdownNow() and does not wait for the workers to end.
WARNING
Cancelling a call does not undo what the tool already did. If a tool had sent a request that changes something, the request may still arrive after the timeout. Treat a timeout on a write as "unknown outcome", and check before you retry. The next lesson shows how to gate such tools.
TIP
Picture it: you send three couriers to three shops and call two of them back when the first one returns with the parcel you needed. A courier who is already inside the shop may still buy the item before the phone rings; one who has stopped to read his phone turns back at once. Calling them back is a request. The analogy stops where a courier would at least answer the phone; a tool stuck in code that never checks for interrupts will not.
Limit concurrency where the resource is scarce
Virtual threads are cheap and there is no pool, so nothing limits how many calls go out. A pool of 4 used to double as "at most 4 requests to that API at once". With one thread per call you must say it yourself. The lab uses a Semaphore with maxConcurrent permits: a call takes a permit before it runs and gives it back after.
Figure 7. Six calls, two permits
How to read this: all six calls exist at once, but only two packets reach the API. The dashed arrow shows the rest parked until a permit comes back.
The wait for a permit counts against the step deadline, not against a call's own timeout. A test shows the difference: with one permit and two calls that each take 600 ms against a call timeout of 1000 ms, the second call finishes 1200 ms after the step began and still succeeds, because its own clock started when it got the permit.
TIP
Picture it: a car park with two spaces and a queue at the barrier. The queue length is whatever it is; the number of cars inside never exceeds two. The analogy stops where a barrier is first-come-first-served; the lab's semaphore does not promise any order for waiting calls.
What not to parallelise
Parallel calls are safe when the calls are independent and read-only, and risky otherwise.
Do not run in parallel
Why
A call that needs the output of another
It cannot start until the first returns. The model usually knows this and asks in separate steps.
Writes that depend on each other, or touch the same record
The order of effects is part of the meaning.
Calls to an API with a rate limit lower than your fan-out
Use maxConcurrent, or the API will answer with errors.
A destructive action that needs a human approval
One approval per call, handled before it runs (next lesson).
Figure 8. Should these calls run at the same time?
flowchart TD
accTitle: Decision guide for parallel tool calls
accDescr: Start with the calls of one reply. If one needs another's output, run in order. If any call writes and the writes are related, run in order. If the target API has a rate limit, run in parallel with a concurrency limit. Otherwise run in parallel.
A["Calls of one model reply"] --> B{"Does one need another's output?"}
B -- yes --> C["Run in order"]
B -- no --> D{"Do related writes happen?"}
D -- yes --> C
D -- no --> E{"Is an API rate-limited?"}
E -- yes --> F["Parallel with a concurrency limit"]
E -- no --> G["Parallel"]
How to read this: start at the top and follow the answers. Only the last two boxes run together.
The loop in this lab is deliberately simple: it runs every call of a reply together. A production agent would put the "related writes" check in front of the executor, using the risk classes from the next lesson.
Structured concurrency: a sketch, and what Java 25 says
Structured concurrency means a group of tasks that live inside one block of code and end before the block does, so a failed block cannot leave a stray task behind. Java has an API for it, StructuredTaskScope. The lab does not use it, and here is why.
I tried to read JEP 505, the proposal for this API, at openjdk.org/jeps/505, and the page returned an HTTP 403 error, so I cite nothing from it.
What I did read is the Java SE 25 API page for StructuredTaskScope on docs.oracle.com, and it opens with: "StructuredTaskScope is a preview API of the Java platform. Programs can only use StructuredTaskScope when preview features are enabled."
I also checked it myself on JDK 25.0.3: compiling a small program that imports it without --enable-preview fails with "StructuredTaskScope is a preview API and is disabled by default". With --enable-preview it compiled and ran. So in Java 25 it is a preview API, and a lab that must build with plain --release 25 cannot use it.
This is the shape of the API, from the Javadoc's usage example, adapted to the lab's tool names. I compiled a version of it once with --enable-preview on JDK 25; it is not part of the lab and not under test.
Notice what the default does: if either subtask fails, join() throws, which is the opposite of the lab's rule that one failing tool must not stop the others. An agent usually wants the lab's behaviour, so even where the API is final you would configure it, or keep an executor like this one. Re-check the status before you rely on either choice: preview APIs can change or move.
Run it
From the repository's examples/backend folder:
./gradlew :labs:agent-parallel:test# 16 tests
./gradlew -q :labs:agent-parallel:run # four runs
Demo prints no durations. Every number is a count or a configured limit: "most calls in flight at once" is counted by a wrapper around each tool, and calls are held at a latch so that all of them must be running before any can finish. Wall-clock numbers vary from machine to machine; counts do not.
Expected output, captured from a real run (Java 25):
Run 1. One reply asks for three tools: the sequential loop and the parallel loop
sequential loop: most calls in flight at once: 1
parallel loop: most calls in flight at once: 3
parallel trace (results are in the order of the calls, c1 c2 c3):
step 1 model asks for get_alert(alert_id=A-1042)
step 1 model asks for query_metric(metric=db_pool_in_use, service=payments-gateway)
step 1 model asks for search_logs(service=payments-gateway, text=deploy)
step 1 tool get_alert -> alert A-1042: checkout-api p99 latency 4200 ms (SLO 800 ms), error rate 6.1%, firing since 02:47 UTC
step 1 tool query_metric -> db pool in use 50 of 50 since 02:44, 14 of 50 at 02:30
step 1 tool search_logs -> 02:41:05 INFO deploy v412 started (previous version v411) | 02:41:40 INFO deploy v412 reported healthy
step 2 final The payments-gateway deploy v412 filled its database pool, which slowed checkout-api.
Run 2. One tool fails and one hangs: the others finish and the model reads both errors
step 1 model asks for get_alert(alert_id=A-1042)
step 1 model asks for query_metric(metric=no_such_metric, service=checkout-api)
step 1 model asks for search_logs(service=payments-gateway, text=deploy)
step 1 model asks for search_runbook(topic=pool)
step 1 tool get_alert -> alert A-1042: checkout-api p99 latency 4200 ms (SLO 800 ms), error rate 6.1%, firing since 02:47 UTC
step 1 error query_metric -> the tool failed: no metric no_such_metric for checkout-api
step 1 error search_logs -> timed out after 200 ms
step 1 tool search_runbook -> Connection pool exhaustion: 1) check for a deploy in the last hour, 2) if there is one, roll it back (needs on-call approval), 3) if not, restart the service (needs on-call approval).
step 2 final Two of the four checks gave no data (a wrong metric name and a log search that timed out).
stop: FINAL_ANSWER after 2 model calls
hung tools that received the interrupt: 1
Run 3. The step deadline passes: the hung calls are cancelled, the finished one keeps its result
step 1 model asks for get_alert(alert_id=A-1042)
step 1 model asks for search_logs(service=payments-gateway, text=deploy)
step 1 model asks for query_metric(metric=db_pool_in_use, service=payments-gateway)
step 1 tool get_alert -> alert A-1042: checkout-api p99 latency 4200 ms (SLO 800 ms), error rate 6.1%, firing since 02:47 UTC
step 1 error search_logs -> cancelled: the step deadline of 300 ms passed
step 1 error query_metric -> cancelled: the step deadline of 300 ms passed
step 2 final Only the alert text came back in time; I will ask again for the logs and the metric.
hung tools that received the interrupt: 2
Run 4. Six calls to a tool that allows two at a time
limit: 2, most calls in flight at once: 2
results: [r1, r2, r3, r4, r5, r6], errors: 0
Reading the output, top to bottom.
Run 1. The sequential loop (the Agent of the agent loop lab) never has more than one call in flight. The parallel loop has all three. The results are listed in call order, c1 c2 c3, and the model answers in the second step. The tools are held at a latch until all three are in flight, so "3" is proved, not hoped for.
Run 2. The second call fails with an ordinary message, the third hangs and ends as timed out after 200 ms, and the other two return results. The model's answer mentions both problems. The last line says the hung tool received the interrupt: the timeout cancelled it, it did not just stop waiting.
Run 3. The call timeout is long, so only the step deadline matters. The finished call keeps its result, the two hung calls are cancelled with a message that names the deadline, and both hung tools received the interrupt.
Run 4. Six calls and a limit of two. The barrier in the wrapped tool lets calls through in pairs, so the run can only finish if exactly two are in flight at a time. The highest count is 2 and all six results come back in order.
The model's answers in runs 1 to 3 are scripted. A real model might ask for the failing metric again, or answer from what it has; the lesson's code only guarantees what the model is given.
Replay the interesting parts one step at a time:
One parallel step, three ways it can go (interactive when JavaScript is on)
Happy path (Run 1)
1. One reply, three calls. The model asks for get_alert (c1), query_metric (c2) and search_logs (c3) in a single reply.
2. Fan out. All three run at the same time. The wrapper counted most calls in flight at once: 3 for the parallel loop and 1 for the sequential loop.
3. Join in call order. The trace lists the results in the order of the calls: get_alert, query_metric, search_logs, each with its own id.
4. Next model call. The model sees all three results and answers: the payments-gateway deploy v412 filled its database pool, which slowed checkout-api.
A failure and a hang (Run 2)
1. Four calls. get_alert, query_metric with a metric that does not exist, search_logs and search_runbook run together with a call timeout of 200 ms.
2. One tool throws. query_metric becomes an error result: the tool failed: no metric no_such_metric for checkout-api. Its siblings are not affected.
3. One tool hangs. search_logs never returns. After 200 ms the watchdog interrupts it and the result is: timed out after 200 ms. The hung tool did receive the interrupt (1).
4. The rest finish. get_alert and search_runbook return normal results. Four results, two of them errors, go back to the model.
5. The model reads both errors. It answers that two of the four checks gave no data: a wrong metric name and a log search that timed out.
Step deadline (Run 3)
1. Three calls, a long call timeout. The call timeout is 30 seconds but the whole step has a deadline of 300 ms. get_alert, search_logs and query_metric start together.
2. One answers. get_alert returns its alert text well before the deadline and keeps its result.
3. Two hang. search_logs and query_metric do not return. At 300 ms the step stops waiting.
4. Cancel. Both unfinished calls become: cancelled: the step deadline of 300 ms passed. Both hung tools received the interrupt (2).
5. The model decides. It answers that only the alert text came back in time and that it will ask again for the logs and the metric.
Under the hood
Three layers are at work.
In your code:threads.submit(...) hands a task to the virtual-thread executor and returns a Future. future.get(timeout) blocks the calling thread (the agent loop) until the task finishes or the time is up. future.cancel(true) marks the future cancelled and interrupts the thread that runs it.
In the JVM: a virtual thread runs on a carrier thread and steps off it when it blocks in an operation that supports that. The watchdog and the workers are all virtual threads, so a hundred calls with a hundred watchdogs do not need two hundred operating-system threads. Which blocking calls release the carrier, and which pin it, is documented in the virtual threads lesson; test your HTTP client the same way before you rely on it.
In the conversation: the model's reply contained several ToolCalls, each with an id. Your loop sends back one ToolResult per id. The lab keeps them in call order. How a provider's API represents several calls in one reply differs by provider, so the lab uses its own small Message type; the Spring AI lesson and LangChain4j lesson show what each framework does with it.
Whether a given model asks for several tools in one reply is up to the model and the way you describe your tools. If it asks for one at a time, this executor has nothing to fan out, and the lesson's pattern then belongs in your workflow code rather than in the loop; see the workflow patterns lesson.
Break it
Three experiments, each run for real against the lab. Restore the code after each one.
1. Replace the virtual threads with a small pool. In ParallelToolExecutor.java, change Executors.newVirtualThreadPerTaskExecutor() to Executors.newFixedThreadPool(2) and run allCallsOfOneReplyAreRunningAtTheSameTime. It fails: expected: <true> but was: <false>. Four calls need to be running at once to open the latch, and a pool of two threads can only start two, so the other two never begin. This is the old problem the virtual threads remove, and it is why the pool size used to be a tuning decision.
2. Forget to cancel. Delete the line futures.forEach(future -> future.cancel(true)); and run theStepDeadlineCancelsUnfinishedSiblingsAndKeepsTheResultsThatArrived. It fails with java.lang.IllegalStateException: Task has not completed: the code asks for the result of a future that never finished. Cancelling is not only tidy, it is what turns "still running" into a result the loop can hand to the model.
3. Leak a permit. Delete permits.release(); and run aPermitIsGivenBackWhenAToolFails. It fails with expected: <fine> but was: <cancelled: the step deadline of 5000 ms passed>: with one permit, the first call that finished kept it, so every later call waited until the step deadline. One missing line in a finally turns a healthy tool into a stuck one.
Restore each change and run the tests again before you go on.
In practice: Parcelo
TriageDesk's first step in the incident is read-only and independent: the alert text, two metrics and a log search. That is the ideal case for parallel calls. The fourth call in the demo shows the realistic one, a tool that fails, a tool that hangs and two that work.
Figure 9. One Parcelo step with a wrong metric name and a hung log search
How to read this: the red dashed arrows are failures that still arrive at the join as ordinary results. The model reads two errors and two answers and decides what to do next.
NOTE
On call, 3 a.m.: Tomasz is the on-call engineer at Parcelo. His triage agent used to look at four things in a row, and the slowest was the runbook search. Moving to parallel reads shortened the step to the time of that one slow call. What surprised him was a log search that failed, which he had never noticed because the sequential version stopped at the first error. The parallel version showed him the three other answers as well. Invented example.
Architect's notes
Bound everything that can wait. A call timeout, a step deadline and a concurrency limit are three separate settings; a production agent needs all three. Pick the numbers from measurements of your own tools.
Parallel calls shorten a step, not a run. The model call between steps is still sequential, and a loop with many steps stays slow.
Fan-out multiplies load. Six calls at once are six requests to the same dependency. Size maxConcurrent from what the dependency can take, and prefer one limit per dependency over one limit for all.
Cancellation needs tool cooperation. Review each tool for how it blocks. Test that an interrupt really stops it, as the lab's tests do for sleeping and waiting code.
A timeout on a write means unknown outcome. Make writes idempotent or check state before retrying.
Return partial results. A step that gives the model three answers and two clear errors is more useful than a step that fails as a whole.
Log each call's start, end and outcome with its id. A parallel trace is hard to read without them. The next lessons build on that.
Common mistakes
Mistake: a timeout per call and no step deadline. Fix: set both; the deadline is what bounds the step when many calls wait for permits.
Mistake: returning results in the order they finished. Fix: join in call order and keep the id.
Mistake: a pool of virtual threads. Fix: one virtual thread per call, with a Semaphore where a limit is needed.
Mistake:try (ExecutorService e = ...) around calls to tools that ignore interrupts. Fix: closing waits for all tasks, so one stuck tool hangs the step; stop waiting with a deadline and shutdownNow(), as the lab does.
Mistake: swallowing InterruptedException. Fix: let it end the tool, or restore the interrupt flag.
Mistake: proving concurrency with sleeps and stopwatch numbers. Fix: use latches and counters ("all calls started before any finished").
Mistake: parallelising writes that depend on each other. Fix: run them in order; use the decision guide in Figure 8.
IMPORTANT
Remember this:
Fan out, join in call order, and keep each result's id.
A timeout limits one call; a deadline limits the whole step. You need both.
Cancellation is a request: the tool has to notice the interrupt.
A semaphore, not a thread count, limits calls to a scarce resource.
Every failure, timeout and cancellation becomes a result the model can read.
Key takeaways
Tool calls are I/O bound, so overlapping them shortens a step to the time of its slowest call.
Virtual threads make one thread per call cheap; there is no pool to size.
The lab's executor isolates failures, applies a per-call timeout and a step deadline, cancels unfinished calls and limits concurrency with a Semaphore.
In Java 25, StructuredTaskScope is a preview API that needs --enable-preview, so the lab uses an executor instead.
Prove concurrency with latches and counters, never with wall-clock numbers.
Practice exercises
Starter. In ParallelToolExecutorTest, change withoutALimitAllSixCallsOverlap to eight calls and make it pass. Then lower maxConcurrent to 3 and read how the test fails.
Intermediate. Add a retries setting to ParallelConfig in ParallelToolExecutor.java: a call that fails with an exception is retried once, but a timed-out call is not. Write the test with a latch, not with sleeps.
Advanced. Make maxConcurrent per tool name: a Map from tool name to permits, so search_logs can be limited to 2 while get_alert is not limited. Add a test that two tools with different limits keep their own highest in-flight count.
Lesson 10 of 15 · Agentic AI for Java Developers: Build and Ship Agents
Run an agent's tool calls in parallel on Java 25 virtual threads, with a per-call timeout, a step deadline, cancellation and a concurrency limit, in a lab.
In the rest of this lesson
Failures stay inside their own call
Timeouts and deadlines are two different clocks
Cancellation is a request, not a command
Limit concurrency where the resource is scarce
What not to parallelise
Structured concurrency: a sketch, and what Java 25 says
Enrolling is free. It unlocks every lesson in Agentic AI for Java Developers: Build and Ship Agents, tracks your progress across devices and keeps your quiz scores. The newsletter is optional.
Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.
Get new articles by email
Free. We email a confirmation link first, and you can unsubscribe from any email.