Reactive Programming vs Virtual Threads in Java: How to Choose
The same trip quote written with Project Reactor and with virtual threads and structured concurrency: concurrency, timeouts, fallbacks, bounded fan-out and stack traces compared. Where each model wins, how to mix them safely, and a decision guide.
kvi5hnuCode Sprout team member8 min readOn this page
Virtual threads and reactive programming solve the same core problem: serving many concurrent I/O-bound operations without one platform thread per waiting operation. Reactive libraries do it by never blocking, and chaining work as callbacks on a few threads. Virtual threads do it by making blocking cheap. This article puts the two side by side on the same task, and then turns the comparison into a decision guide.
The same quote, twice
The task: price a trip by looking up a flight and a hotel concurrently, apply a timeout of 1 second, return a fallback if anything fails, and price six routes with at most four quotes in flight at once. Both versions finish by showing what a failure's stack trace contains.
Reactor
Needs reactor-core. This was run with Reactor 3.7.6 on Java 25.
import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
// Needs reactor-core (io.projectreactor:reactor-core:3.7.x) on the class path
public class ReactiveQuote {
static Mono<Integer> flight(String route) {
return Mono.just(100 + route.chars().sum() % 400).delayElement(Duration.ofMillis(100));
}
static Mono<Integer> hotel(String city) {
return Mono.just(city).delayElement(Duration.ofMillis(150)).map(c -> {
if (c.isEmpty()) throw new IllegalArgumentException("no city");
return 95;
});
}
static Mono<String> quote(String route, String city) {
return Mono.zip(flight(route), hotel(city)) // both run concurrently
.map(t -> route + ": " + (t.getT1() + 3 * t.getT2()))
.timeout(Duration.ofSeconds(1))
.onErrorResume(e -> Mono.just(route + ": no quote (" + e.getMessage() + ")"));
}
public static void main(String[] args) {
System.out.println("1. " + quote("LIS-OSL", "Oslo").block());
System.out.println("2. " + quote("LIS-XXX", "").block());
// 3. Many quotes, at most 4 in flight at once
List<String> routes = List.of("LIS-OSL", "LIS-TOS", "OSL-TOS", "OPO-OSL", "FAO-OSL", "LIS-BGO");
System.out.println("3. " + Flux.fromIterable(routes).flatMapSequential(r -> quote(r, "Oslo"), 4).collectList().block());
// 4. What a failure's stack trace shows
try {
Mono.zip(flight("LIS-OSL"), hotel("")).block();
} catch (RuntimeException e) {
Throwable cause = e instanceof IllegalArgumentException ? e : e.getCause();
StackTraceElement[] trace = cause.getStackTrace();
long ours = Arrays.stream(trace).filter(f -> f.getClassName().startsWith("ReactiveQuote")).count();
System.out.println("4. stack trace of the failure: " + trace.length + " frames, " + ours + " from this program:");
for (StackTraceElement f : trace) System.out.println(" at " + f.getClassName() + "." + f.getMethodName());
}
}
}
Output:
1. LIS-OSL: 500
2. LIS-XXX: no quote (no city)
3. [LIS-OSL: 500, LIS-TOS: 508, OSL-TOS: 514, OPO-OSL: 506, FAO-OSL: 482, LIS-BGO: 478]
4. stack trace of the failure: 10 frames, 1 from this program:
at ReactiveQuote.lambda$hotel$0
at reactor.core.publisher.FluxMap$MapSubscriber.onNext
at reactor.core.publisher.MonoDelayElement$DelayElementSubscriber.run
at reactor.core.scheduler.SchedulerTask.call
at reactor.core.scheduler.SchedulerTask.call
at java.util.concurrent.FutureTask.run
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run
at java.util.concurrent.ThreadPoolExecutor.runWorker
at java.util.concurrent.ThreadPoolExecutor$Worker.run
at java.lang.Thread.run
Virtual threads and structured concurrency
The Java 27 preview API (java --enable-preview VirtualQuote.java on Java 27, no flag on Java 28). Blocking calls are written as plain Thread.sleep here, standing in for JDBC or HTTP calls.
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Semaphore;
import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.StructuredTaskScope.Joiner;
import java.util.concurrent.StructuredTaskScope.Subtask;
// Java 27 preview API (java --enable-preview VirtualQuote.java); final in Java 28
public class VirtualQuote {
static int flight(String route) throws InterruptedException {
Thread.sleep(100); // a blocking call: cheap on a virtual thread
return 100 + route.chars().sum() % 400;
}
static int hotel(String city) throws InterruptedException {
Thread.sleep(150);
if (city.isEmpty()) throw new IllegalArgumentException("no city");
return 95;
}
static String quote(String route, String city) throws InterruptedException {
try (var scope = StructuredTaskScope.open(cf -> cf.withTimeout(Duration.ofSeconds(1)))) {
Subtask<Integer> flight = scope.fork(() -> flight(route)); // both run concurrently
Subtask<Integer> hotel = scope.fork(() -> hotel(city));
scope.join();
return route + ": " + (flight.get() + 3 * hotel.get());
} catch (ExecutionException e) {
return route + ": no quote (" + e.getCause().getMessage() + ")";
}
}
public static void main(String[] args) throws Exception {
System.out.println("1. " + quote("LIS-OSL", "Oslo"));
System.out.println("2. " + quote("LIS-XXX", ""));
// 3. Many quotes, at most 4 in flight at once
List<String> routes = List.of("LIS-OSL", "LIS-TOS", "OSL-TOS", "OPO-OSL", "FAO-OSL", "LIS-BGO");
Semaphore inFlight = new Semaphore(4);
try (var scope = StructuredTaskScope.open(Joiner.<String>allSuccessfulOrThrow())) {
for (String r : routes) {
scope.fork(() -> {
inFlight.acquire();
try { return quote(r, "Oslo"); } finally { inFlight.release(); }
});
}
System.out.println("3. " + scope.join());
}
// 4. What a failure's stack trace shows
try (var scope = StructuredTaskScope.open()) {
scope.fork(() -> hotel(""));
scope.join();
} catch (ExecutionException e) {
List<String> frames = new ArrayList<>();
for (StackTraceElement f : e.getCause().getStackTrace()) frames.add(f.getClassName() + "." + f.getMethodName());
System.out.println("4. stack trace of the failure: " + frames.size() + " frames, "
+ frames.stream().filter(f -> f.startsWith("VirtualQuote")).count() + " from this program:");
frames.forEach(f -> System.out.println(" at " + f));
System.out.println(" the ExecutionException from join() has the owner's stack, down to "
+ e.getStackTrace()[e.getStackTrace().length - 1].getMethodName() + "()");
}
}
}
Output:
1. LIS-OSL: 500
2. LIS-XXX: no quote (no city)
3. [LIS-OSL: 500, LIS-TOS: 508, OSL-TOS: 514, OPO-OSL: 506, FAO-OSL: 482, LIS-BGO: 478]
4. stack trace of the failure: 4 frames, 2 from this program:
at VirtualQuote.hotel
at VirtualQuote.lambda$main$1
at java.util.concurrent.StructuredTaskScopeImpl$SubtaskImpl.run
at java.lang.VirtualThread.run
the ExecutionException from join() has the owner's stack, down to main()
The JDK frame names in the last lines depend on the release.
Comparing them
| Concern | Reactor | Virtual threads + structured concurrency |
|---|---|---|
| Run two calls concurrently | Mono.zip(a, b) | fork both, join() |
| Timeout | .timeout(d) | withTimeout(d) on the scope |
| Fallback on failure | .onErrorResume(...) | catch (ExecutionException e) |
| Cancel the other call on failure | automatic, when zip fails | automatic: the scope cancels its other subtasks |
| Bounded fan-out | flatMapSequential(fn, 4) | a Semaphore around each subtask |
| Library calls | must be non-blocking (WebClient, R2DBC) | any library: JDBC, HttpClient, files |
| Where code runs | on scheduler threads, chosen by operators | on the virtual thread that called it |
| Failure stack trace | the lambda and the library's operator plumbing | the actual call path in the subtask, plus the owner's stack on join()'s exception |
Both versions are short, and they produce the same results. The differences show up around them.
Debugging
In the Reactor trace, one frame of ten belongs to the program: the lambda inside hotel. Nothing says which pipeline it belonged to or who subscribed. The rest is Reactor's operator plumbing and the scheduler's thread pool. With real pipelines of 15 operators, traces get much longer and say even less. Reactor offers checkpoint() and a debug agent (ReactorDebugAgent) to add assembly information, at a cost.
In the virtual-thread trace, the frames are the call path: hotel called from the subtask's lambda. The ExecutionException thrown by join() has the owner's stack, down to main. Debuggers step through the code line by line, and profilers and thread dumps (article 36) show what each request is doing.
Thinking and maintenance
Reactive code is a different programming model. Loops, try/catch, early returns and local variables have to be expressed with operators, and every method on the path must return a Mono or Flux. A single blocking call in the wrong place stalls an event loop (article 44). Thread-local context doesn't follow the pipeline, so libraries use Reactor's Context instead. None of this is impossible, but it costs training and review effort for every developer.
With virtual threads, the code is ordinary Java. The concurrency is visible in one place (the scope), and everything else is sequential.
Where reactive still wins
- Streams of events. Merging feeds, windows and sliding averages, sampling, debouncing,
groupBy: Reactor has tested operators for all of these. With virtual threads, you'd write those loops and buffers yourself. - Built-in flow control. Demand-driven backpressure across a whole pipeline, and integration with protocols that carry demand, such as RSocket and some messaging clients (article 46).
- Existing reactive stacks. A working WebFlux or R2DBC service gains little from a rewrite. Its benefits are already there.
- Very high connection counts with mostly idle streams, such as server-sent events to many clients, where a non-blocking server keeps memory use low per connection.
Where virtual threads win
- Request/response services: call a few databases and services, combine, respond. That's most backend code.
- Blocking libraries: JDBC, JPA/Hibernate, most SDKs, file I/O. They work as they are.
- Teams and tools: debuggers, profilers, stack traces, exception handling and code review all work as usual.
- Incremental adoption: switching an executor or a server setting (articles 9 and 48) moves existing code to virtual threads.
Choosing

Neither model helps CPU-bound work: there's no waiting to overlap. Use parallel streams, ForkJoinPool, or a pool sized to the number of cores (article 22).
Mixing the two
The models can coexist in one application:
- Blocking on a reactive result from a virtual thread is fine.
mono.block()on a virtual thread parks it cheaply, which makes reactive clients usable from blocking code. - Blocking on an event-loop thread is never fine. Don't call
block(), JDBC orThread.sleepinside a reactive pipeline running on a Reactor or Netty thread. If a reactive pipeline must call blocking code, wrap it inMono.fromCallable(...)and move it withsubscribeOn(Schedulers.boundedElastic()), which Reactor can back with virtual threads (article 45). - Use one model per request path. A controller that is half reactive and half blocking combines the costs of both.
What's current
- Java 21 made virtual threads final, Java 24 removed
synchronizedpinning (JEP 491), and Java 28 makes structured concurrency final (JEP 543). Together they cover the request/response cases that reactive frameworks were largely adopted for. - Spring Boot runs Spring MVC on virtual threads with one property, and Quarkus runs
@RunOnVirtualThreadendpoints on them (articles 48 and 49). WebFlux and Mutiny remain fully supported for reactive code. - Reactor (3.8 since November 2025) and RxJava 3 are actively maintained. Reactive programming isn't going away. It's becoming a specialised tool for stream processing rather than the default for scalability.
Common questions
Are virtual threads faster than reactive code? For typical I/O-bound request/response work, throughput is comparable: both keep CPUs busy while I/O is pending. Reactive code can use less memory per connection in extreme cases. Virtual threads usually win on development and debugging time.
Should I rewrite my WebFlux service with virtual threads? Only if the reactive model is causing real problems: bugs from blocking calls, slow onboarding, hard-to-debug incidents. A stable reactive service is not a reason to rewrite.
Do virtual threads make R2DBC pointless? For new request/response code, JDBC on virtual threads is simpler and has more mature drivers and tools. R2DBC still fits fully reactive stacks that stream results with backpressure.
Can I use structured concurrency inside a reactive application?
Yes, on a virtual thread, for example in a blocking-style endpoint. Don't open scopes and join() on event-loop threads, because join() blocks.
Summary
- Reactive libraries scale by never blocking and chaining operators on a few threads. Virtual threads scale by making blocking cheap.
- For the same request/response task, both versions are short, but the virtual-thread version uses any library, keeps ordinary control flow, and produces stack traces that show the real call path.
- Reactive code still wins for event-stream processing with operators and demand-driven flow control, and for existing reactive stacks.
- Mix the models carefully: blocking on a virtual thread is fine, blocking on an event loop never is. Keep one model per request path.
- CPU-bound work needs neither: size a pool to the cores.
Practice questions
A team's Spring WebFlux service calls a legacy SOAP library that only has a blocking API. Requests intermittently stall. What's the likely cause, and what are the options?
Answer
The blocking SOAP call runs on a Netty event-loop thread and stalls every request served by that loop. The options: wrap the call in Mono.fromCallable(...).subscribeOn(Schedulers.boundedElastic()), possibly backed by virtual threads, or move that endpoint, or the whole service, to Spring MVC on virtual threads, where blocking calls are fine.
You need to merge price feeds from three exchanges, compute a 5-second moving average per symbol, and alert when it moves by more than 1%. Which model would you start with, and why?
Answer
A reactive library. The task is event-stream processing: merge, groupBy, time windows and backpressure for fast feeds are ready-made operators, while a virtual-thread version would need hand-written buffers, timers and synchronization for every window.
Why is mono.block() acceptable in one place and a serious bug in another?
Answer
block() blocks the calling thread until the result arrives. On a virtual thread, that's cheap: the thread unmounts and its carrier serves other work. On a Reactor or Netty event-loop thread, it stalls every connection the loop serves, and if the result is meant to be delivered by that same loop, it can deadlock. Reactor protects its own non-blocking schedulers: calling block() on a parallel() thread throws IllegalStateException ("block()/blockFirst()/blockLast() are blocking, which is not supported in thread parallel-1").
Review quiz
Test yourself on Part 6 with the Part 6 review quiz: Reactive Java and Virtual Threads. It covers blocking and non-blocking I/O, NIO buffers and selectors, event loops, CompletableFuture, reactive streams, backpressure and choosing between the models.
Previous: Backpressure in Java: Flow Control With Reactive Streams and Virtual Threads
Next: Virtual Threads in Spring Boot: Configuration, Pitfalls and Monitoring

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.