Event-Driven Java: Event Loops, Callbacks and CompletableFuture
How event-driven frameworks such as Netty and Vert.x run application handlers on a few event-loop threads, why a single blocking call stalls them, and how asynchronous APIs evolved from nested callbacks to composable CompletableFuture pipelines with error handling and timeouts.
kvi5hnuCode Sprout team member8 min readOn this page
The selector server in article 43 mixed three jobs in one class: the event loop, the protocol, and the business logic. Event-driven frameworks separate them. Netty, Vert.x, and the servers under Spring WebFlux and Quarkus provide the loop and the protocols, and call your handlers when an event arrives: a request, a message, a timer. This article looks at what that means for application code, and at the asynchronous APIs that code has to use.
Handlers run on the I/O threads

A framework runs a small number of event-loop threads, usually one or two per CPU core, and assigns each connection to one of them. Your handler is called on that loop thread. While it runs, the loop can't do anything else for any of its connections. Hence the one rule of event-driven code: a handler must never block. No Thread.sleep, no JDBC call, no blocking HTTP client, no future.get(), no synchronized block that might wait.
What a handler does instead:
- Starts an asynchronous operation and registers what should happen when it completes.
- Schedules a timer instead of sleeping. Vert.x's
vertx.setTimer(...)is the framework version of theloop.schedule(...)in the demo below. - Offloads unavoidable blocking work to a worker pool (Vert.x
executeBlocking, ReactorMono.fromCallable(...).subscribeOn(Schedulers.boundedElastic())), and continues on the loop when the result arrives. - Sends a message to another component instead of calling it directly. Vert.x's event bus delivers messages by address, within one process or across a cluster, so components stay decoupled and each handler still runs on an event loop. The reply arrives as another event.
Frameworks help you notice violations. Vert.x logs a "blocked thread" warning when a handler holds an event loop for more than 2 seconds by default, and Reactor's BlockHound agent fails the test when blocking calls happen on non-blocking threads.
Asynchronous APIs
A synchronous method returns its result: Flight flight = findFlight(route). An asynchronous one returns immediately, and delivers the result later. Java code has used three shapes for that:
- Callbacks:
findFlight(route, onResult, onError). - Futures:
CompletableFuture<Flight> findFlight(route), a handle that completes later and can be composed. - Reactive streams:
Mono<Flight>orFlux<Fare>, for zero, one or many results over time, with backpressure (articles 45 and 46).
One trip, four ways
The demo runs a single-threaded "event loop" (a scheduled executor with one thread), shows what blocking it does, and then prices a trip (flight, then a loyalty discount that depends on the flight, plus a hotel) with callbacks, with CompletableFuture, and with blocking calls on a virtual thread.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.Consumer;
public class Solution {
record Flight(String route, int fare) {}
record Hotel(String city, int nightly) {}
// ---------- 1. An event loop: one thread runs every handler ----------
static final ScheduledExecutorService loop =
Executors.newSingleThreadScheduledExecutor(r -> Thread.ofPlatform().name("event-loop").daemon().unstarted(r));
static long now() { return System.nanoTime() / 1_000_000; }
/** Submits a handler that blocks, or one that schedules its continuation, then measures a fast event behind it. */
static void loopDemo(String label, boolean blocking) throws Exception {
long start = now();
loop.execute(() -> {
if (blocking) {
try { Thread.sleep(500); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
} else {
loop.schedule(() -> { }, 500, TimeUnit.MILLISECONDS); // "call me back in 500 ms"
}
});
CompletableFuture<Long> fast = new CompletableFuture<>();
loop.execute(() -> fast.complete(now() - start));
long waited = fast.get();
System.out.println(" " + label + (waited >= 450 ? "the next event waited for it" : "the next event ran at once"));
}
// ---------- 2. Callback-style API ----------
static void findFlight(String route, Consumer<Flight> onResult, Consumer<Throwable> onError) {
loop.schedule(() -> onResult.accept(new Flight(route, 212)), 100, TimeUnit.MILLISECONDS);
}
static void findHotel(String city, Consumer<Hotel> onResult, Consumer<Throwable> onError) {
loop.schedule(() -> {
if (city.equals("Atlantis")) onError.accept(new IllegalArgumentException("unknown city " + city));
else onResult.accept(new Hotel(city, 95));
}, 100, TimeUnit.MILLISECONDS);
}
static void loyaltyDiscount(Flight flight, Consumer<Integer> onResult, Consumer<Throwable> onError) {
loop.schedule(() -> onResult.accept(flight.fare() / 10), 100, TimeUnit.MILLISECONDS);
}
// ---------- 3. The same APIs returning CompletableFuture ----------
static CompletableFuture<Flight> flightAsync(String route) {
CompletableFuture<Flight> f = new CompletableFuture<>();
findFlight(route, f::complete, f::completeExceptionally);
return f;
}
static CompletableFuture<Hotel> hotelAsync(String city) {
CompletableFuture<Hotel> f = new CompletableFuture<>();
findHotel(city, f::complete, f::completeExceptionally);
return f;
}
static CompletableFuture<Integer> loyaltyDiscountAsync(Flight flight) { // depends on the flight
CompletableFuture<Integer> f = new CompletableFuture<>();
loyaltyDiscount(flight, f::complete, f::completeExceptionally);
return f;
}
static CompletableFuture<String> tripAsync(String route, String city, int nights) {
return flightAsync(route)
.thenCompose(flight -> loyaltyDiscountAsync(flight) // sequential: needs the flight
.thenApply(discount -> flight.fare() - discount))
.thenCombine(hotelAsync(city), // parallel: started right away
(flightPrice, hotel) -> flightPrice + nights * hotel.nightly())
.thenApply(total -> route + " + " + nights + " nights in " + city + ": " + total)
.orTimeout(2, TimeUnit.SECONDS)
.exceptionally(e -> "no quote (" + rootCause(e).getMessage() + ")");
}
static Throwable rootCause(Throwable e) {
return e instanceof CompletionException && e.getCause() != null ? e.getCause() : e;
}
// ---------- 4. Blocking code on a virtual thread, for comparison ----------
static String tripBlocking(String route, String city, int nights) throws Exception {
Flight flight = flightAsync(route).get(); // just wait: cheap on a virtual thread
int discount = loyaltyDiscountAsync(flight).get();
Hotel hotel = hotelAsync(city).get();
return route + " + " + nights + " nights in " + city + ": " + (flight.fare() - discount + nights * hotel.nightly());
}
public static void main(String[] args) throws Exception {
System.out.println("1. a handler that takes 500 ms:");
loopDemo("blocking with sleep(): ", true);
loopDemo("scheduling a continuation: ", false);
CompletableFuture<String> nested = new CompletableFuture<>();
findFlight("LIS-OSL", flight ->
loyaltyDiscount(flight, discount ->
findHotel("Oslo", hotel ->
nested.complete("LIS-OSL + 3 nights in Oslo: "
+ (flight.fare() - discount + 3 * hotel.nightly())),
nested::completeExceptionally),
nested::completeExceptionally),
nested::completeExceptionally);
System.out.println("2. callbacks: " + nested.get());
System.out.println("3. CompletableFuture: " + tripAsync("LIS-OSL", "Oslo", 3).get());
System.out.println(" with a failure: " + tripAsync("LIS-ATL", "Atlantis", 3).get());
CompletableFuture<String> never = new CompletableFuture<String>().orTimeout(200, TimeUnit.MILLISECONDS);
try {
never.join();
} catch (CompletionException e) {
System.out.println(" orTimeout: " + (e.getCause() instanceof TimeoutException ? "TimeoutException" : e));
}
try (ExecutorService vt = Executors.newVirtualThreadPerTaskExecutor()) {
System.out.println("4. blocking, virtual: " + vt.submit(() -> tripBlocking("LIS-OSL", "Oslo", 3)).get());
}
}
}
Output:
1. a handler that takes 500 ms:
blocking with sleep(): the next event waited for it
scheduling a continuation: the next event ran at once
2. callbacks: LIS-OSL + 3 nights in Oslo: 476
3. CompletableFuture: LIS-OSL + 3 nights in Oslo: 476
with a failure: no quote (unknown city Atlantis)
orTimeout: TimeoutException
4. blocking, virtual: LIS-OSL + 3 nights in Oslo: 476
1. Blocking the loop
A handler that called Thread.sleep(500) held the only loop thread, so the next event, which needed no time at all, waited half a second. A handler that scheduled its continuation returned at once, and the next event ran immediately. Scale that up to a loop serving 10,000 connections, and one blocking call delays all of them.
2. Callbacks
The callback version works, but look at its shape: each step that depends on the previous one nests one level deeper. Three steps produce a pyramid of lambdas, often called callback hell. And every level needs its own error path (nested::completeExceptionally appears three times). Running the hotel search in parallel with the flight, or adding a timeout, would mean shared state between the callbacks.
3. CompletableFuture
CompletableFuture turns the pyramid into a flat pipeline:
| Method | Use it for |
|---|---|
thenApply(fn) | transforming a result |
thenCompose(fn) | a next step that is itself asynchronous and depends on the result: flight, then discount |
thenCombine(other, fn) | joining two independent operations that run in parallel: flight price and hotel |
exceptionally(fn), handle(fn) | recovering from a failure anywhere earlier in the chain |
orTimeout(d, unit), completeOnTimeout(v, d, unit) | failing, or completing with a default, after a deadline (Java 9) |
allOf(...), anyOf(...) | waiting for many futures, or the first |
The Atlantis hotel search failed, the failure skipped the remaining stages, and exceptionally turned it into a fallback answer. The exception arrives wrapped in a CompletionException, hence rootCause. orTimeout completed a future that would never finish with a TimeoutException.
One detail matters on event loops: where stages run. A non-async stage such as thenApply runs on whichever thread completes the previous stage, here the loop thread, or, if that stage has already completed, right away on the thread that calls thenApply. That's fine for cheap work, but heavy computation in a thenApply blocks the loop just like sleep does. The ...Async(fn, executor) variants run a stage on an executor of your choice.
4. Blocking on a virtual thread
The last version simply waited for each step with get(), top to bottom, on a virtual thread. It produced the same quote, and waiting cost almost nothing because the virtual thread unmounted while blocked. With structured concurrency (Part 4), the flight and hotel would run in parallel too, with cancellation on failure.
What asynchronous code costs
- Readability. Control flow moves into lambdas. Loops,
try/catchand early returns have to be rebuilt from operators. - Debugging. Stack traces show the thread that completed a stage, not the code that started the operation. The original caller is long gone.
- Context. Thread-locals such as a logging context don't follow the stages from thread to thread (article 38), so frameworks add context-propagation hooks.
- Colour. Once a method returns a future, its callers must handle a future too, all the way up. Mixing in one blocking call breaks the model.
Before virtual threads, these were the price of scalability. With virtual threads, plain blocking code scales for request/response work, which is what article 47 weighs.
From single values to streams
A CompletableFuture holds one value. Many problems produce sequences: price ticks, Kafka records, rows streamed from a database, server-sent events. Callbacks and futures don't express "many values over time", and they can't tell a fast producer to slow down. That's the job of reactive streams, the subject of article 45.
What's current
CompletableFutureis unchanged through Java 27, apart from small additions over the years (Java 9:orTimeout,completeOnTimeout,delayedExecutor; Java 12:exceptionallyCompose; Java 19:resultNow,exceptionNow,state).- Vert.x 4.5 and later can deploy verticles on virtual threads, where handlers may block on Vert.x futures with
await. Netty-based frameworks are adding similar options for running handlers off the event loop. - Reactive endpoints in Spring WebFlux and Quarkus still run on event loops. For blocking-style code, Spring Boot can run Spring MVC on virtual threads, and Quarkus runs endpoints annotated
@RunOnVirtualThreadon them (articles 48 and 49).
Common questions
Is an event loop the same as a thread pool? No. A pool runs independent tasks on many threads, and blocking one task just occupies one thread. An event loop multiplexes many connections on one thread, so blocking one handler stalls all of them.
Why not just make the event loop bigger? More loop threads help with CPU-bound work, but they don't solve blocking: if handlers block, you need as many threads as concurrent blocking calls, and you're back to thread-per-request.
Does CompletableFuture.supplyAsync(task) without an executor run on the event loop?
No, on ForkJoinPool.commonPool(), which is meant for CPU-bound work. Blocking there starves other users of the common pool. Pass an explicit executor for anything that blocks.
When are callbacks still fine? For a single, independent completion notification, such as "log when the write finishes". As soon as steps depend on each other, futures or reactive types compose better.
Summary
- Event-driven frameworks run a few event-loop threads and call application handlers on them. A handler that blocks stalls every connection on its loop.
- Handlers start asynchronous work, schedule timers, or offload blocking calls to worker pools, and continue when results arrive.
- Callbacks nest and duplicate error handling.
CompletableFuturecomposes steps withthenCompose,thenCombine,exceptionallyandorTimeout. - Non-async stages run on the completing thread, which may be the event loop. Use the
...Asyncvariants for heavy work. - Futures hold one value. Streams of values with flow control need reactive streams.
Practice questions
A Vert.x handler calls a JDBC repository directly, and under load all requests slow down, including ones that never touch the database. Explain why, and give two fixes.
Answer
The JDBC call blocks the event-loop thread, so every other connection served by that loop waits until the query returns. Fix it by running the query on a worker pool (executeBlocking) and continuing on the loop with the result, by using a non-blocking database client, or by running that handler on a virtual thread, as Vert.x 4.5+ allows.
What's the difference between thenApply and thenCompose? When do you need thenCompose?
Answer
thenApply transforms a result with a plain function, T -> U. thenCompose takes a function that returns another future, T -> CompletableFuture<U>, and flattens it. You need thenCompose when the next step is itself asynchronous, like fetching a discount that depends on the flight. With thenApply you'd get a CompletableFuture<CompletableFuture<U>>.
In a CompletableFuture chain on an event loop, thenApply(this::renderPdf) takes 800 ms of CPU. What's the problem, and how do you fix it?
Answer
The stage runs on the thread that completed the previous stage, which is likely the event-loop thread, so rendering blocks the loop for 800 ms. Use thenApplyAsync(this::renderPdf, renderPool) with a pool sized for CPU-bound work, and continue the I/O part of the pipeline after it.
Previous: Java NIO Selectors: Building an Event-Loop Server
Next: Reactive Streams in Java: Publisher, Subscriber and the Flow API

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.