Reactive Programming vs Virtual Threads in Java: Trade-offs and the Promise of Project Loom
What reactive frameworks such as Reactor and Spring WebFlux solve, what they cost in learning, debugging and lock-in, and how virtual threads offer the same scalability for blocking code. Includes a Reactor version of a request and 10,000 concurrent requests on virtual threads.
kvi5hnuCode Sprout team member10 min readOn this page
By the end of the 2010s, Java developers who needed to handle many concurrent requests had two choices. They could keep simple blocking code and accept that platform threads limit how many requests run at once. Or they could go reactive: rewrite the code as non-blocking pipelines that never hold a thread while waiting. Reactive frameworks delivered real scalability, at a real price. This article looks at both sides, then at the third option that Java 21 made available: virtual threads.
The reactive idea
Reactive programming treats a computation as a stream of events that flows through a pipeline of operators. Nothing blocks. When data isn't ready, the pipeline simply doesn't run, and the thread goes off to do other work. When the data arrives (a network packet, a database row), an event triggers the next stage. A handful of event-loop threads can serve tens of thousands of connections this way.
The main Java implementations are Project Reactor (behind Spring WebFlux), RxJava, Eclipse Vert.x and Akka/Pekko. They share the Reactive Streams specification, which Java 9 adopted as java.util.concurrent.Flow. Part 6 explains the model in depth, including non-blocking I/O and backpressure.
The trip quote, reactive
Here is the running example written with Reactor. Our five calls are blocking, so each one is wrapped with Mono.fromCallable and moved to Reactor's scheduler for blocking work. A fully reactive application would use non-blocking clients (such as WebClient or R2DBC) instead.
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
import java.time.Duration;
public class ReactiveQuote {
record Traveler(long id, String homeCity) {}
record Flight(String route, int price) {}
record Hotel(String name, int price) {}
record Quote(int total, String note) {}
// Wrap each blocking call so it runs on Reactor's scheduler for blocking work
static <T> Mono<T> blocking(java.util.concurrent.Callable<T> call) {
return Mono.fromCallable(call).subscribeOn(Schedulers.boundedElastic());
}
static Mono<Quote> quote(long id) {
Mono<Traveler> traveler = blocking(() -> loadTraveler(id)).cache(); // fetch once, share
Mono<Flight> flight = traveler.flatMap(t -> blocking(() -> findFlight(t)));
Mono<Hotel> hotel = traveler.flatMap(t -> blocking(() -> findHotel(t)));
Mono<Boolean> search = blocking(() -> { recordSearch(id); return true; });
return Mono.zip(flight, hotel, search) // subscribes to all three at once
.flatMap(all -> blocking(() -> price(all.getT1(), all.getT2())))
.timeout(Duration.ofSeconds(1), Mono.just(new Quote(0, "timed out, try again")))
.onErrorResume(e -> Mono.just(new Quote(0, "unavailable: " + e.getMessage())));
}
public static void main(String[] args) {
quote(1).block(); // warm-up: class loading, scheduler threads
long start = System.nanoTime();
Quote q = quote(7).block(); // block only at the very edge, in main
System.out.println(q + " in about " + Math.round((System.nanoTime() - start) / 1e8) * 100 + " ms");
}
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); 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(), "priced"); }
static void waitFor(long millis) {
try { Thread.sleep(millis); }
catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IllegalStateException(e); }
}
}
With reactor-core 3.7 on the class path (Maven coordinates io.projectreactor:reactor-core), this prints:
Quote[total=600, note=priced] in about 300 ms
It looks a lot like the CompletableFuture version, with different names: a Mono is a stream of at most one value, flatMap starts a dependent asynchronous step, zip waits for several. But two details show how differently reactive code behaves:
- Nothing happens until someone subscribes.
quote(7)only describes the work;block()(or, in a server, the framework) subscribes and starts it. AMonothat's never subscribed never runs. - Each subscription runs the work again. Without
.cache(),flightandhotelwould each subscribe totraveler, and the traveler would be loaded twice. And if the search call were chained in aflatMapafter pricing, laziness would delay its start until then, and the request would take 400 ms instead of 300 ms. Both mistakes compile and produce the right answer, just slower or with duplicate calls. That's typical of reactive bugs.
What reactive programming costs
Reactive frameworks are powerful, and for streaming data, event-driven systems and very high connection counts, they're often the right tool. But they bring costs that teams frequently underestimate:
A steep learning curve. Publishers, subscribers, operators, schedulers, hot versus cold streams and backpressure are new concepts for developers trained on imperative code. Reactor alone has hundreds of operators, and choosing the right one takes experience.
Cognitive load. Business logic turns into chains of lambdas and higher-order functions. Simple control flow, such as a loop with an early exit, a try/catch or an if around a remote call, becomes a combination of operators. Code reviews get harder when only some of the team is fluent.
Debugging. A stack trace from inside a pipeline shows scheduler threads and operator internals, not the request that started the work. When a pipeline combines four sources, an error raised in the combining step often doesn't say which upstream source caused it. Breakpoints and step-through debugging help little, because execution jumps between threads and callbacks. Frameworks offer special tools (Reactor's checkpoint() and debug agent) to compensate, which is one more thing to learn.
Overengineering. Powerful composition makes it tempting to build elaborate pipelines for problems that a few sequential calls would solve.
Mismatch. Many applications are plain request–response: receive a request, make three calls, return a response. The reactive model's strengths (streams, backpressure, event-driven flows) don't help much there, while its costs remain. And one blocking call in the wrong place, such as a JDBC driver or a legacy library, can stall an event loop and the thousands of connections it serves.
Lock-in. The ideas transfer between frameworks, but the APIs don't. Moving from RxJava to Reactor, or away from reactive altogether, means rewriting. Hiring is harder too, and reactive types (Mono, Flux) tend to spread through every layer's method signatures.
None of this means reactive programming is wrong. It means it's a trade-off: you buy scalability by paying in complexity. The question Project Loom asked was whether Java could provide the scalability without the complexity.
The promise of virtual threads
Project Loom's answer, final in Java 21, is the virtual thread: a java.lang.Thread implemented by the JVM rather than the operating system. Three properties make it work:
- They're cheap. A virtual thread starts with a tiny stack stored on the Java heap and costs roughly as much as a small object graph. You can create millions of them. There's no reason to pool them: create one per task.
- Blocking is cheap. When a virtual thread blocks on I/O,
sleep, a lock or a queue, the JVM saves its stack and unmounts it from the platform thread that was running it. That platform thread, called a carrier, immediately runs another virtual thread. When the I/O completes, the virtual thread is mounted again, possibly on a different carrier, and continues where it left off. - They're ordinary threads. The same
ThreadAPI, the same blocking libraries, the sametry/catch, the same debuggers and profilers. Stack traces show the whole request again.
The carriers are platform threads in a dedicated ForkJoinPool, by default one per CPU core, so virtual threads inherit work stealing for free.

The effect is that the thread-per-request style, simple blocking code, scales like asynchronous code. Waiting no longer costs a scarce OS thread.
The smallest possible migration
If code already uses an ExecutorService, moving its tasks to virtual threads can be a one-line change:
// before: a shared pool of platform threads
ExecutorService executor = Executors.newFixedThreadPool(200);
// after: a new virtual thread for every task
ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor();
The program below serves 10,000 concurrent trip-quote requests. Each request runs on its own virtual thread and fans out three more, so about 40,000 virtual threads are alive at the peak. Every call still blocks for 100 ms with plain Thread.sleep:
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
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 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); 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()); }
// The same blocking fan-out as with a thread pool; only the executor changed
static Quote quote(long id) throws InterruptedException, ExecutionException {
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
Traveler traveler = loadTraveler(id);
Future<Flight> flight = executor.submit(() -> findFlight(traveler));
Future<Hotel> hotel = executor.submit(() -> findHotel(traveler));
executor.submit(() -> recordSearch(id));
return price(flight.get(), hotel.get());
} // close() waits for recordSearch as well
}
public static void main(String[] args) throws Exception {
int requests = 10_000;
long start = System.nanoTime();
List<Future<Quote>> results = new ArrayList<>();
try (ExecutorService server = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < requests; i++) {
long id = i;
results.add(server.submit(() -> quote(id))); // one virtual thread per request
}
}
long ms = (System.nanoTime() - start) / 1_000_000;
long sum = 0;
for (Future<Quote> f : results) sum += f.resultNow().total();
System.out.println("requests served: " + results.size());
System.out.println("every quote is 600: " + (sum == 600L * requests));
System.out.println("virtual threads used: about " + requests * 4);
System.out.println("finished in under 3 seconds: " + (ms < 3_000));
System.out.println("a platform pool of 200 threads would need at least "
+ (requests / 200) * 300 / 1000.0 + " s");
}
static void waitFor(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException("interrupted", e);
}
}
}
Output:
requests served: 10000
every quote is 600: true
virtual threads used: about 40000
finished in under 3 seconds: true
a platform pool of 200 threads would need at least 15.0 s
On a laptop the whole run takes about half a second: all 10,000 requests wait at the same time, and each takes its minimum of 300 ms. The comparison line is simple arithmetic: with 200 platform threads, one per request, only 200 requests can be in progress, so 10,000 of them need at least 50 rounds of 300 ms. (Creating 40,000 platform threads instead would hit the limits from article 3.)
Notice the per-request try (ExecutorService executor = ...) in quote. That was an anti-pattern with platform-thread pools, but with virtual threads it's the natural style, because there's nothing expensive to reuse. The executor's lifetime is the request's lifetime.
The benefits, and what's still to learn
Virtual threads deliver three things together:
- Resource efficiency. Millions of concurrent tasks without exhausting memory or OS threads.
- Simple code. Blocking, sequential, imperative code with ordinary exceptions and stack traces. There's no new programming model to learn.
- Good utilization. Carriers never sit idle while there's a ready virtual thread, so the CPU stays busy.
They aren't magic, and the rest of this course covers what you still need to know. Virtual threads make waiting cheap, not computing: CPU-bound work still needs parallelism, and they don't make any single request faster. Some situations stop a virtual thread from unmounting (pinning). Abundant threads make it easy to overwhelm a database, so you still limit access to scarce resources. And ThreadLocal-heavy code needs rethinking. Part 2 covers all of these, and Parts 4 and 5 cover the two APIs designed to go with virtual threads: structured concurrency and scoped values.
What's current
- Virtual threads are final since Java 21 (JEP 444). Java 24 (JEP 491) removed the most common cause of pinning: virtual threads can now unmount while holding a
synchronizedmonitor. - Spring Boot (
spring.threads.virtual.enabled=true), Quarkus (@RunOnVirtualThread), Helidon 4, Jetty, Tomcat and others can run request handlers on virtual threads. Part 7 covers them. - Reactive frameworks remain actively developed and are still a strong choice for streaming and event-driven workloads. Part 6 compares the two approaches in detail.
Common questions
Do virtual threads make reactive programming obsolete? Not entirely. They remove the main reason most teams adopted it: scaling request–response code that blocks. Reactive streams still shine for data that really is a stream, for backpressure between producers and consumers, and in codebases already built on them.
Is the per-request executor in quote wasteful?
No. A virtual-thread-per-task executor holds no pooled threads, so creating and closing one costs very little. Its close() also gives each request a clear boundary: the request can't finish while one of its subtasks is still running.
Do I need to change my blocking libraries for virtual threads?
Usually not. JDK networking, sockets, HttpClient, Thread.sleep, java.util.concurrent locks and queues all unmount the virtual thread while they wait. JDBC drivers and other libraries written in plain Java work too. Article 14 covers the exceptions: native code, class initialization and file I/O, which hold the carrier while they wait.
Why is the reactive example's .cache() needed?
A Mono runs its work again for every subscriber. Two dependent steps (flight and hotel) subscribe to traveler, so without cache() the traveler would be loaded twice.
Summary
- Reactive frameworks scale by never blocking a thread: work is a pipeline of operators driven by events.
- They cost a steep learning curve, harder debugging, more complex code, a poor fit for simple request–response logic, and framework lock-in.
- Reactive pipelines are lazy and re-run per subscription, which causes subtle performance bugs.
- Virtual threads are cheap JVM-managed threads that unmount from their carrier while blocked, so simple blocking code scales.
- Moving an executor-based design to virtual threads can be as small as switching to
Executors.newVirtualThreadPerTaskExecutor(). - Virtual threads make waiting cheap, not computing. Pinning, resource limits and thread-locals still need care.
Practice questions
A reactive method returns Mono<Order>, and a caller writes orderService.place(order); without using the result. What happens?
Answer
Nothing is placed. A Mono is lazy: it describes the work, and nothing runs until something subscribes. The caller must return the Mono to the framework, compose it into its own pipeline, or subscribe.
Why is it fine to create a new newVirtualThreadPerTaskExecutor() per request, but not a new newFixedThreadPool(5)?
Answer
A fixed pool's value is reusing expensive platform threads; creating one per request pays the thread-creation cost every time and multiplies the total thread count. A virtual-thread executor pools nothing: each task gets a new cheap virtual thread either way, so a per-request executor costs almost nothing and gives the request's subtasks a clear lifetime.
A server's 8 carrier threads all run CPU-heavy image resizing on virtual threads. What happens to requests that only need a quick database lookup?
Answer
They wait. Virtual threads release their carrier when they block, not while they compute, so 8 busy computations occupy all 8 carriers until they finish or block. Virtual threads don't add CPU capacity. CPU-heavy work should be bounded, for example by running it on a separate pool sized to the cores.
Review quiz
Test yourself on Part 1 with the Part 1 review quiz: Threads, Executors and the Road to Virtual Threads. Twenty questions cover concurrency versus parallelism, thread creation and interruption, the costs of platform threads, fan-out, executors and futures, false sharing, CompletableFuture and reactive trade-offs.
Previous: Java ForkJoinPool and CompletableFuture: Work Stealing and Composable Async Code
Next: What Is a Java Virtual Thread? Platform Threads, Virtual Threads and How They Differ

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.