Blocking I/O and Parallel Fan-Out in Java: Speeding Up a Request With Raw Threads
Why a request that makes several blocking calls is slow, how running independent calls on separate threads cuts its latency, how to pass results back safely with join and AtomicReference, and the failures, leaks and missing cancellation that make hand-made threads a poor long-term answer.
kvi5hnuCode Sprout team member8 min readOn this page
A thread that waits on a database or a remote service isn't doing anything useful, but it can't do anything else either. When one request makes several such calls one after another, their waiting times add up. If some of those calls don't depend on each other, they can wait at the same time. This is called fan-out: split a request into independent calls, run them concurrently, then combine the results.
This article does fan-out the oldest way, with hand-made threads. It works, and it shows clearly which problems later tools (executors, CompletableFuture, structured concurrency) had to solve.
The request we want to speed up
Our running example prices a trip for a traveler. It makes five calls, each standing in for a 100 ms database query or HTTP request:
Quote quoteSequentially(long id) {
Traveler traveler = loadTraveler(id); // database: 100 ms
Flight flight = findFlight(traveler); // airline API: 100 ms
Hotel hotel = findHotel(traveler); // hotel API: 100 ms
recordSearch(id); // analytics: 100 ms
return price(flight, hotel); // pricing service: 100 ms
}
That's 500 ms per request, and during almost all of it the thread is blocked: parked by the OS, waiting for bytes to arrive. It isn't using the CPU, but it can't serve anyone else either.
Finding what can run in parallel
The calls aren't all independent. Draw the dependencies before starting threads:
findFlightandfindHotelneed theTraveler, so they come afterloadTraveler.recordSearchneeds only the ID. It doesn't produce anything the quote needs.priceneeds both the flight and the hotel.
So after loadTraveler, three calls can overlap, and price waits for two of them:

The best possible time is the length of the longest dependency chain, here three calls or about 300 ms. No amount of extra threads beats that.
Fan-out with raw threads
Each independent call gets its own thread. The tricky part is getting results back: a Runnable returns nothing, so each thread stores its result in a shared holder, and the caller reads it after join():
Quote quoteWithThreads(long id) throws InterruptedException {
Traveler traveler = loadTraveler(id);
var flightRef = new AtomicReference<Flight>();
var hotelRef = new AtomicReference<Hotel>();
Thread flightThread = new Thread(() -> flightRef.set(findFlight(traveler)), "flight");
Thread hotelThread = new Thread(() -> hotelRef.set(findHotel(traveler)), "hotel");
Thread searchThread = new Thread(() -> recordSearch(id), "search-log");
flightThread.start();
hotelThread.start();
searchThread.start();
flightThread.join(); // wait only for the two results we need
hotelThread.join();
Quote quote = price(flightRef.get(), hotelRef.get());
searchThread.join(); // don't return while background work is still running
return quote;
}
Why is reading the result safe? Java's memory model guarantees that everything a thread did before it terminated is visible to a thread that returns from join() on it. That's what makes flightRef.get() see the value. An AtomicReference (or a volatile field) adds a guarantee that matters if you read the value without joining, and it documents that the variable is shared between threads. A plain local variable can't be used at all, because a lambda can only capture effectively final variables.
Why join searchThread at the end? Otherwise the method returns while one of its subtasks is still running. Nobody would ever learn whether it failed, and it would keep running even if the caller had moved on. Keeping every subtask inside the method that started it is the core idea of structured concurrency, which Part 4 covers in depth.
Trying it, and breaking it
The program below times both versions, then makes the hotel service fail to show what happens to errors. Times are rounded to the nearest 100 ms:
import java.util.concurrent.atomic.AtomicReference;
public class Solution {
record Traveler(long id, String homeCity) {}
record Flight(String route, int price) {}
record Hotel(String name, int price) {}
record Quote(int total) {}
static volatile boolean hotelServiceDown = false;
// Each call stands in for a 100 ms database query or HTTP call
static Traveler loadTraveler(long id) { waitFor(100); return new Traveler(id, "Oslo"); }
static Flight findFlight(Traveler t) { waitFor(100); return new Flight(t.homeCity() + "-Lisbon", 240); }
static Hotel findHotel(Traveler t) {
waitFor(100);
if (hotelServiceDown) throw new IllegalStateException("hotel service unavailable");
return new Hotel("Casa Azul", 360);
}
static void recordSearch(long id) { waitFor(100); }
static Quote price(Flight f, Hotel h) { waitFor(100); return new Quote(f.price() + h.price()); }
static Quote quoteSequentially(long id) {
Traveler traveler = loadTraveler(id);
Flight flight = findFlight(traveler);
Hotel hotel = findHotel(traveler);
recordSearch(id);
return price(flight, hotel);
}
static Quote quoteWithThreads(long id) throws InterruptedException {
Traveler traveler = loadTraveler(id); // needed by the next two calls
var flightRef = new AtomicReference<Flight>();
var hotelRef = new AtomicReference<Hotel>();
Thread flightThread = new Thread(() -> flightRef.set(findFlight(traveler)), "flight");
Thread hotelThread = new Thread(() -> hotelRef.set(findHotel(traveler)), "hotel");
Thread searchThread = new Thread(() -> recordSearch(id), "search-log");
hotelThread.setUncaughtExceptionHandler((t, e) ->
System.out.println(" [" + t.getName() + " thread died: " + e.getMessage() + "]"));
flightThread.start();
hotelThread.start();
searchThread.start();
flightThread.join();
hotelThread.join();
Flight flight = flightRef.get();
Hotel hotel = hotelRef.get();
if (hotel == null) throw new IllegalStateException("no hotel result, and no idea why");
Quote quote = price(flight, hotel);
searchThread.join();
return quote;
}
public static void main(String[] args) throws InterruptedException {
time("sequential", () -> quoteSequentially(7));
time("three extra threads", () -> {
try { return quoteWithThreads(7); }
catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IllegalStateException(e); }
});
hotelServiceDown = true;
try {
quoteWithThreads(7);
} catch (IllegalStateException e) {
System.out.println("caller sees: " + e.getMessage());
}
}
static void time(String label, java.util.function.Supplier<Quote> work) {
long start = System.nanoTime();
Quote q = work.get();
long ms = (System.nanoTime() - start) / 1_000_000;
System.out.printf("%-20s total=%d about %d ms%n", label, q.total(), Math.round(ms / 100.0) * 100);
}
static void waitFor(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException("interrupted", e);
}
}
}
Output (on a very busy machine, the rounded times may differ):
sequential total=600 about 500 ms
three extra threads total=600 about 300 ms
[hotel thread died: hotel service unavailable]
caller sees: no hotel result, and no idea why
The fan-out cut the request from 500 ms to 300 ms, a 40% reduction in latency, using the same amount of CPU. That's the good news. The second half is the bad news.
System.nanoTime() is the right clock for measuring elapsed time: it is monotonic, unlike System.currentTimeMillis(), which can jump when the system clock is adjusted. For serious performance comparisons use a benchmark harness such as JMH, which handles JIT warm-up and other measurement traps. For 100 ms sleeps, a simple timer is fine.
What's wrong with hand-made threads
The failing run exposes the first problem, and there are several more:
- Errors don't travel back. The hotel exception killed the hotel thread and nothing else. The caller only noticed because the result was missing, and it had to invent its own error message: the real cause was lost. Without the handler we installed, the exception would be printed to standard error, and that's it. Notice also that when the hotel fails, the method throws before
searchThread.join(), so the search thread outlives the method after all. Getting cleanup right on every path needstry/finally, which is exactly what structured concurrency automates. - No cancellation on failure. When the hotel call fails, the flight call keeps running even though its result is now useless. In a real system it keeps holding a connection and a thread.
- No timeout. If the airline API hangs,
flightThread.join()waits forever, and so does the request. - Interruption doesn't propagate. If the request thread is interrupted while waiting in
join(), it gets anInterruptedException, but the three subtask threads keep running. Nobody interrupts them. - Unbounded thread creation. Every request creates three new platform threads. At 1,000 requests per second that's 3,000 thread creations per second, and under a load spike, thousands of live threads, with all the costs from the previous article. Eventually
Thread.start()throwsOutOfMemoryError. - It doesn't scale with the calling thread. The request thread is still blocked for the whole 300 ms, now with three more blocked threads beside it. Fan-out improves latency, but it uses more threads per request, not fewer.
The next articles address these one at a time: executors fix problem 5, Future makes errors travel back (problem 1), CompletableFuture adds composition and timeouts, and structured concurrency (Part 4) fixes problems 1–4 together. Virtual threads (Part 2) make problems 5 and 6 disappear.
What's current
- Since Java 21, the same fan-out can use virtual threads (
Thread.ofVirtual().start(...)orThread.startVirtualThread(...)), which removes the cost of creating threads but not problems 1–4. StructuredTaskScope(preview from Java 21 to 27, final in Java 28) is the purpose-built tool for exactly this pattern: fork the subtasks, join them, propagate the first failure and cancel the rest.
Common questions
Do I need AtomicReference if I always call join() before reading the result?
For visibility, no: join() already guarantees that the worker's writes are visible. But the lambda can't assign a local variable, so you need some mutable holder, and an AtomicReference is the clearest one. It also stays correct if someone later reads the value without joining first.
Why not start a thread for loadTraveler too?
Because the next two calls need its result. Starting a thread and immediately joining it gains nothing and costs a thread. Only calls without a dependency between them can overlap.
How many threads does the fan-out version use per request? Four: the request thread plus three workers. All four are blocked most of the time. The request finishes faster, but the server can hold fewer requests at once if threads are the scarce resource.
Is a 40% improvement typical? It depends entirely on the dependency graph. The best case is the length of the longest chain of dependent calls. If every call depends on the previous one, fan-out gains nothing.
Summary
- A thread blocked on I/O does no work but can't do anything else. Sequential blocking calls add up their waiting times.
- Fan-out runs independent calls concurrently. The lower bound on latency is the longest chain of dependent calls.
join()waits for a thread and makes its writes visible. AnAtomicReferenceis a convenient, safe place to put a result.- Raw threads lose errors, never cancel siblings, have no timeouts, ignore the caller's interruption and create unbounded numbers of threads.
- These shortcomings motivate executors and futures,
CompletableFuture, structured concurrency and virtual threads.
Practice questions
A request makes four calls of 80 ms each: A, then B and C (both need A's result), then D (needs B and C). What is the best possible latency with fan-out?
Answer
About 240 ms: A (80 ms), then B and C in parallel (80 ms), then D (80 ms). The longest dependency chain, A → B → D, has three calls.
In this code, what can go wrong at quote(flightRef.get())?
var flightRef = new AtomicReference<Flight>();
Thread t = new Thread(() -> flightRef.set(findFlight(traveler)));
t.start();
return quote(flightRef.get());
Answer
The method never waits for the thread, so flightRef.get() usually runs before findFlight has finished and returns null. The fix is to call t.join() before reading the result. Even then, a failure in findFlight would leave the reference null with no error attached.
Why does the raw-thread version keep running the flight lookup after the hotel lookup fails?
Answer
The threads know nothing about each other. Nothing connects the failure in one thread to the others, and Java never stops a thread on its own. Something would have to call flightThread.interrupt(), and the flight code would have to respond to the interrupt. Structured concurrency does exactly that automatically.
Previous: The Hidden Cost of Java Platform Threads: Memory, OS Limits and Context Switches
Next: Java Executors and Thread Pools: What They Fix and What They Don't

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.