Sub topic 13
Virtual threads or reactive: choosing an approach
This chapter assumes you know Java 21 basics, java.util.concurrent, and how a Spring MVC application handles a request on a blocking thread. It also assumes you have read the earlier chapters on enabling virtual threads and on which workloads suit them. Here you compare virtual threads with reactive programming (Spring WebFlux and Project Reactor) and decide which fits a given application.
The problem both approaches solve
A blocking call, such as a JDBC query or an HTTP request, holds a thread while it waits. With platform threads, that is expensive. A server can only keep a few hundred to a few thousand of them, so throughput under high concurrency is capped by the pool size, not by CPU.
Two approaches remove that cap:
- Reactive programming never blocks. A small number of threads run an event loop. Code is written as a pipeline of callbacks and operators, and the framework resumes the pipeline when data arrives.
- Virtual threads keep the blocking style. When a virtual thread blocks on I/O, the JVM unmounts it from its carrier thread, and the carrier runs other work.
Both let a few operating-system threads serve many concurrent waiting requests. They differ in how you write the code and in what else changes around it.
Programming model
The most visible difference is how the code reads. Here is the same lookup in each style.
// Spring MVC on virtual threads: sequential, blocking style
@GetMapping("/orders/{id}")
OrderView order(@PathVariable long id) {
Order order = orderRepository.findById(id).orElseThrow();
Customer customer = customerClient.fetch(order.customerId());
return new OrderView(order, customer);
}// Spring WebFlux: composed pipeline
@GetMapping("/orders/{id}")
Mono<OrderView> order(@PathVariable long id) {
return orderRepository.findById(id)
.switchIfEmpty(Mono.error(new NoSuchElementException()))
.flatMap(order -> customerClient.fetch(order.customerId())
.map(customer -> new OrderView(order, customer)));
}The first version uses ordinary control flow. Exceptions are thrown and caught normally. Stack traces show the call path. A debugger steps through it line by line. The second version expresses the same logic as operators. It is concise once you know the vocabulary, but errors, retries, and context propagation all go through the operator chain, and stack traces point into the library internals more than into your own code.
Reactive code also has a stricter rule: nothing in the chain may block. A single blocking JDBC call on an event-loop thread stalls every request on that thread. With virtual threads, blocking is the supported way to write code.
Ecosystem and stack requirements
Switching to reactive is not a local change. The whole call path has to be non-blocking, or you must isolate blocking parts on a separate scheduler.
| Layer | Virtual threads (Spring MVC) | Reactive (Spring WebFlux) |
|---|---|---|
| Web layer | Spring MVC, Tomcat or Jetty | WebFlux, usually Netty |
| Relational database | JDBC, JPA, Hibernate | R2DBC or a reactive driver; JPA does not fit |
| HTTP client | `RestClient`, `RestTemplate`, Apache HttpClient | `WebClient` |
| Existing libraries | Work as they are | Must be non-blocking or wrapped |
| Debugging | Normal stack traces and debugger | Operator stack traces, special tooling |
| Team learning curve | Low | Substantial |
If your application already uses JPA and JDBC, the virtual thread route is a property change plus review. The reactive route is a rewrite of the data and client layers.
Backpressure and streaming
Reactive streams define backpressure. This is a protocol where a slow consumer signals how much data it can accept, so a fast producer does not flood it. It is built into the operator model.
Virtual threads have no equivalent. A virtual thread that blocks on a slow consumer simply waits, which is a form of natural backpressure for simple request and response work. But for continuous streams, such as server-sent events, long-lived data feeds, or processing an unbounded sequence with rate control, reactive types such as Flux give you tools that blocking code does not. You would need to build bounded queues and flow control yourself.
Virtual threads also do not limit concurrency for you. Because they are cheap, a burst of requests can create thousands of them, all hitting your database or a downstream service. As the earlier chapter on concurrency limits showed, you cap that with a Semaphore or a bounded connection pool. Reactive code has related controls, such as flatMap concurrency arguments, but you still have to set them.
Performance: what to expect
For I/O-bound request and response services, both approaches scale to high concurrency with far fewer threads than the classic pool model. Neither is faster per request. Virtual threads raise throughput when requests spend most of their time waiting and the old pool was the limit.
Points to keep in mind:
- Reactive can use slightly less memory per waiting request, because a pipeline is a small object graph, while a virtual thread keeps a stack that grows and shrinks on the heap.
- Virtual threads add no benefit for CPU-bound work. The same holds for reactive code. Both are limited by cores.
- If the real bottleneck is a database connection pool or a slow downstream service, neither approach helps until you address that.
- Measure with your own workload. Published benchmarks vary widely with the I/O pattern, payload size, and driver.
Decision criteria
Choose by looking at your constraints, not by trend.
- Existing code base. A large MVC application on JDBC or JPA points to virtual threads. The cost is low and the risk is limited and reversible, since you can turn the property off.
- Streaming and backpressure needs. Long-lived streams, fan-in of many event sources, and fine-grained flow control favor reactive.
- Team skills. If the team knows blocking Java well and has little reactive experience, virtual threads avoid a long learning period.
- Dependencies. Count the blocking libraries you rely on. Each one is a reason to avoid a full reactive rewrite.
- New projects. For a new service with simple request and response behavior, start with MVC and virtual threads. For a new service that is mostly streaming or gateway-style routing with non-blocking clients, WebFlux is a reasonable start.
- Operational maturity. Reactive systems need monitoring of event-loop blocking. Virtual thread systems need monitoring of pinning and downstream saturation.
Migrating from a reactive application
Moving from WebFlux back to MVC with virtual threads is rarely worth it if the application already works well. Reactive code that is stable and tuned has no pressing reason to change. The common case is the opposite: teams on MVC who considered WebFlux only to escape thread pool limits. For them, virtual threads remove that motivation.
Common mistakes
- Treating virtual threads as a speed-up. They raise concurrency, not single-request speed.
- Forgetting limits. Without a semaphore or pool bound, a burst can overload a database that the thread pool used to protect.
- Mixing blocking and reactive carelessly. Calling
block()inside a reactive pipeline on an event-loop thread fails or stalls the loop. - Ignoring pinning. Blocking inside
synchronizedon Java 21 holds the carrier thread, which erases the benefit under load. - Choosing reactive only for scale. If the only goal is handling many waiting requests, the blocking style on virtual threads reaches it with less code.
Exercise
A team runs a Spring MVC service with JPA and a blocking REST client. Under load, requests queue because the 200-thread Tomcat pool is full while CPU stays at 15 percent. A developer proposes rewriting the service in WebFlux. Which approach would you recommend, and what must you add if you choose it?
Show answer
Recommend virtual threads. The service is I/O-bound, the pool is the limit, and JPA and the blocking client work unchanged, so setting spring.threads.virtual.enabled=true avoids a rewrite. Because the thread pool no longer caps concurrency, add a limit such as a Semaphore or a bounded connection pool in front of the database and downstream services, and check for pinning from synchronized blocks that block.
Exercise
Name two requirements for which reactive programming is still the better fit than virtual threads.
Show answer
Streaming workloads that need built-in backpressure and flow control, such as server-sent events or processing unbounded event sources, and stacks that are already fully non-blocking, such as a Netty-based gateway using WebClient and R2DBC, where a rewrite would bring nothing.