Contents
Virtual Threads vs WebFlux: Why the Choice Is Not as Clear as You Think

Virtual Threads vs WebFlux: It Is Not Black and White

Since Java 21, the same opinion has appeared at conferences, on LinkedIn and in team discussions: “Virtual threads solved everything; WebFlux is dead.”

That is not true. This article explains why.

Both approaches address the same problem: how to serve thousands of concurrent requests without bringing a server to its knees. They do it in fundamentally different ways, and each has situations where it is the better choice.

Quick overview: how do they work?

Virtual threads (Project Loom, Java 21+)

Traditional thread:
┌──────────────────┐
│   OS Thread       │  ← 1 MB stack, expensive context switch
│   (platform)      │  ← Count limited by OS (~2000-5000)
└──────────────────┘

Virtual Thread:
┌──────────────────┐
│  Virtual Thread   │  ← ~Few KB stack, cheap
│  (JVM managed)    │  ← Count: millions
│       │           │
│  ┌────▼────┐      │
│  │ Carrier │      │  ← When a virtual thread blocks on I/O, the JVM unmounts it
│  │ Thread  │      │     and the carrier can serve another virtual thread
│  └─────────┘      │
└──────────────────┘

You write ordinary imperative code (such as Thread.sleep() and blocking I/O), while the JVM handles efficiency. When a virtual thread encounters a blocking operation, the JVM unmounts it from its carrier thread, which can serve another virtual thread.

WebFlux (Project Reactor)

Event Loop (Netty):
┌──────────────────────────────────┐
│  Event Loop Thread (1-N cores)   │
│                                  │
│  Request A ──▶ Handler ──▶ DB   │
│  Request B ──▶ Handler ──▶ API  │  ← Everything is non-blocking
│  Request C ──▶ Handler ──▶ DB   │  ← No waiting
│                                  │
│  Callback ◀── DB Response A     │
│  Callback ◀── API Response B    │
└──────────────────────────────────┘

You write reactive code using Mono<T> and Flux<T>. Nothing blocks. Everything is event-driven, and a small number of threads serves many requests.

Comparison in numbers

MetricVirtual threads (Tomcat)WebFlux (Netty)
100 concurrent usersComparableComparable
1,000 concurrent usersComparableSlightly better
10,000 concurrent usersVery goodBetter throughput
100,000+ concurrent usersDegradationStill stable
Memory per connection~a few KB~a few hundred bytes
DebuggingStandard toolsA nightmare
Stack tracesReadableUnreadable
Learning curveLowHigh

When to choose virtual threads

1. Conventional CRUD microservices

java
// ✅ Virtual Threads: Clean, readable code
@RestController
@RequestMapping("/api/orders")
public class OrderController {

    @GetMapping("/{id}")
    public OrderDto getOrder(@PathVariable Long id) {
        // Blocking call — the JVM handles it for you
        Order order = orderRepository.findById(id)
            .orElseThrow(() -> new NotFoundException("Order not found"));

        // Another blocking call
        Customer customer = customerService.getCustomer(order.getCustomerId());

        // Synchronous logic
        return OrderDto.from(order, customer);
    }
}
java
// ❌ WebFlux: Unnecessary complexity for this use case
@RestController
@RequestMapping("/api/orders")
public class OrderController {

    @GetMapping("/{id}")
    public Mono<OrderDto> getOrder(@PathVariable Long id) {
        return orderRepository.findById(id)
            .switchIfEmpty(Mono.error(new NotFoundException("Order not found")))
            .flatMap(order ->
                customerService.getCustomer(order.getCustomerId())
                    .map(customer -> OrderDto.from(order, customer))
            );
    }
}

For 90% of enterprise applications, the virtual-thread version is easier to read and debug, and equally performant.

2. An existing Spring MVC application

yaml
# application.yml — enable virtual threads with one property
spring:
  threads:
    virtual:
      enabled: true

That is all: no rewrite or migration. Your existing MVC app automatically uses virtual threads.

3. When the team does not know reactive programming

java
// WebFlux debugging: What happened?
reactor.core.Exceptions$ErrorCallbackNotImplemented:
    java.lang.NullPointerException
    Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException:
    Error has been observed at the following site(s):
        *__checkpoint ⇢ Handler ...OrderController#getOrder(Long)
        |_ ...somewhere in the reactive pipeline...

versus

java
// Virtual Threads debugging: Clear stack trace
java.lang.NullPointerException: Cannot invoke "Customer.getName()"
    at com.app.service.OrderService.getOrder(OrderService.java:42)
    at com.app.controller.OrderController.getOrder(OrderController.java:28)

If your team has two years of Spring MVC experience and none with reactive programming, virtual threads are the clear choice.

When to choose WebFlux

1. Streaming and server-sent events

java
// ✅ WebFlux: Native streaming with backpressure
@GetMapping(value = "/stream/events", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<ServerSentEvent<EventDto>> streamEvents() {
    return eventService.getEventStream()
        .map(event -> ServerSentEvent.<EventDto>builder()
            .id(String.valueOf(event.getId()))
            .event("update")
            .data(EventDto.from(event))
            .build()
        );
}

WebFlux has native support for backpressure: if the client cannot process data fast enough, the server slows down. With virtual threads you would need to implement that logic yourself.

2. GraphQL subscriptions

java
// ✅ WebFlux: GraphQL subscriptions are reactive by nature
@DgsSubscription
public Publisher<Notification> onNotification(
        @InputArgument String userId) {

    return notificationService.getNotificationStream(userId)
        .filter(n -> n.getUserId().equals(userId));
}

GraphQL subscriptions return Publisher<T>, a reactive type. WebFlux with Netty is a native environment for this use case. With virtual threads you would need to convert between blocking and reactive approaches.

3. Massive numbers of concurrent WebSocket connections

If you serve 100,000+ persistent WebSocket connections for chat, real-time dashboards or gaming, WebFlux with Netty remains more efficient. Its event-loop model avoids the overhead of unmounting and remounting virtual threads.

4. Complex asynchronous composition

java
// ✅ WebFlux: Composition of parallel operations
public Mono<DashboardDto> getDashboard(String userId) {
    Mono<UserProfile> profile = userService.getProfile(userId);
    Mono<List<Order>> orders = orderService.getRecentOrders(userId);
    Mono<WalletBalance> balance = walletService.getBalance(userId);
    Mono<List<Notification>> notifications = notificationService.getUnread(userId);

    return Mono.zip(profile, orders, balance, notifications)
        .map(tuple -> DashboardDto.builder()
            .profile(tuple.getT1())
            .orders(tuple.getT2())
            .balance(tuple.getT3())
            .notifications(tuple.getT4())
            .build()
        );
}

Mono.zip() starts all four calls in parallel and waits for them. Virtual threads can do this too (with StructuredTaskScope), but Reactor's operators are more mature for this pattern.

Virtual thread pitfalls

Virtual threads are not a silver bullet. Here are problems you may encounter.

1. Thread pinning (synchronized blocks)

java
// ❌ PROBLEM: synchronized blocks the carrier thread
public synchronized String getFromCache(String key) {
    // The virtual thread is pinned — the carrier thread waits
    return cache.get(key);
}

// ✅ SOLUTION: Use ReentrantLock
private final ReentrantLock lock = new ReentrantLock();

public String getFromCache(String key) {
    lock.lock();
    try {
        return cache.get(key);
    } finally {
        lock.unlock();
    }
}

If your code or libraries use synchronized blocks, virtual threads can become pinned to carrier threads, losing their advantage. JDBC drivers and some connection pools have had this problem; check your versions.

2. Connection pool exhaustion

java
// ❌ PROBLEM: 100,000 virtual threads but only 50 DB connections
// Result: 99,950 threads wait for a connection

// ✅ SOLUTION: Use a semaphore as protection
private static final Semaphore DB_LIMITER = new Semaphore(50);

public Order getOrder(Long id) {
    DB_LIMITER.acquire();
    try {
        return orderRepository.findById(id).orElseThrow();
    } finally {
        DB_LIMITER.release();
    }
}

Virtual threads let you create millions of threads, but your database connection pool may still have only 50–200 connections. Without limits, you can overwhelm the database.

3. ThreadLocal memory leak

java
// ❌ PROBLEM: ThreadLocal with a million virtual threads = memory leak
private static final ThreadLocal<ExpensiveObject> TL =
    ThreadLocal.withInitial(ExpensiveObject::new);

// ✅ SOLUTION: Use ScopedValue (Java 21+)
private static final ScopedValue<RequestContext> CONTEXT = ScopedValue.newInstance();

WebFlux pitfalls

1. Spring Security @PreAuthorize

java
// ❌ PROBLEM: @PreAuthorize does not work with reactive parameter types
@PreAuthorize("hasRole('ADMIN')")
@GetMapping("/admin/users")
public Flux<UserDto> getUsers() {
    // Works, but only for simple role-based checks
    return userService.getAllUsers();
}

// ❌ PROBLEM: Complex expression-based checks
@PreAuthorize("@authService.canAccess(#id)")
@GetMapping("/orders/{id}")
public Mono<OrderDto> getOrder(@PathVariable Long id) {
    // authService.canAccess() must return Mono<Boolean>?
    // No — @PreAuthorize expects a synchronous boolean!
    // You must either:
    // 1. Call .block() in authService (an anti-pattern)
    // 2. Move security logic into the reactive chain
    return orderService.getOrder(id);
}

In practice, it looks like this:

java
// Workaround: Security logic directly in the reactive chain
@GetMapping("/orders/{id}")
public Mono<OrderDto> getOrder(@PathVariable Long id) {
    return ReactiveSecurityContextHolder.getContext()
        .map(ctx -> ctx.getAuthentication())
        .flatMap(auth -> {
            // Manual authorization in the reactive chain
            if (!authService.canAccessOrder(auth, id)) {
                return Mono.error(new AccessDeniedException("Forbidden"));
            }
            return orderService.getOrder(id);
        });
}

A loss of elegance. Instead of a simple annotation, manual security code is scattered through controllers.

java
// ✅ Virtual Threads: @PreAuthorize works normally
@PreAuthorize("@authService.canAccess(#id)")
@GetMapping("/orders/{id}")
public OrderDto getOrder(@PathVariable Long id) {
    return orderService.getOrder(id);
    // authService.canAccess() is a synchronous method
    // Everything works out of the box
}

2. Lost SecurityContext in a new Mono chain

One subtle WebFlux pitfall is that ReactiveSecurityContextHolder stores authentication in the Reactor Context, propagated through a reactive chain. Once you create a new disconnected Mono, the context is lost.

java
// ❌ PROBLEM: SecurityContext is lost with a new Mono
@GetMapping("/orders/{id}")
public Mono<OrderDto> getOrder(@PathVariable Long id) {
    return orderService.getOrder(id)
        .flatMap(order -> {
            // Enrich the order with data from another service
            // Create a new Mono — and the SecurityContext is gone!
            Mono<EnrichmentData> enrichment = enrichmentService.enrich(order);

            return enrichment.map(data -> {
                // Here ReactiveSecurityContextHolder.getContext()
                // returns EMPTY — authentication is lost
                return OrderDto.from(order, data);
            });
        });
}
java
// ❌ PROBLEM: Scheduler switches threads; context is not propagated
@GetMapping("/report")
public Mono<ReportDto> getReport() {
    return ReactiveSecurityContextHolder.getContext()
        .flatMap(ctx -> {
            String username = ctx.getAuthentication().getName();
            return reportService.generate(username);
        })
        .subscribeOn(Schedulers.boundedElastic());
        // ^ The scheduler switches to another thread
        // SecurityContext sa nepreniesol!
}
java
// ✅ WORKAROUND: Manual propagation via Reactor Context
@GetMapping("/orders/{id}")
public Mono<OrderDto> getOrder(@PathVariable Long id) {
    return ReactiveSecurityContextHolder.getContext()
        .flatMap(securityContext -> {
            Authentication auth = securityContext.getAuthentication();
            // Explicitly pass authentication to each sub-chain
            return orderService.getOrder(id)
                .flatMap(order -> enrichmentService.enrich(order, auth)
                    .map(data -> OrderDto.from(order, data))
                );
        });
}

In the imperative world of virtual threads this problem does not exist: SecurityContextHolder is ThreadLocal and works automatically throughout the request scope.

java
// ✅ Virtual Threads: SecurityContext is always available
@GetMapping("/orders/{id}")
public OrderDto getOrder(@PathVariable Long id) {
    // SecurityContextHolder.getContext() works anywhere
    Order order = orderService.getOrder(id);
    EnrichmentData data = enrichmentService.enrich(order);
    return OrderDto.from(order, data);
    // No manual context propagation
}

3. Blocking libraries in a reactive pipeline

java
// ❌ PROBLEM: Calling blocking code in WebFlux
@GetMapping("/report")
public Mono<ReportDto> generateReport() {
    return Mono.fromCallable(() -> {
        // Toto blokuje event loop thread!
        byte[] pdf = pdfGenerator.generate();  // blocking I/O
        String url = s3Client.upload(pdf);      // blocking I/O
        return new ReportDto(url);
    }).subscribeOn(Schedulers.boundedElastic()); // ← Required workaround
}

If even one library in the chain blocks (JDBC, some SDKs or PDF generators), you need to wrap it using Schedulers.boundedElastic(). Most real projects have at least two or three blocking dependencies.

4. Testing is painful

java
// Virtual Threads: Ordinary test
@Test
void shouldGetOrder() {
    Order order = orderService.getOrder(1L);
    assertEquals("Pizza", order.getName());
}

// WebFlux: StepVerifier ceremony
@Test
void shouldGetOrder() {
    StepVerifier.create(orderService.getOrder(1L))
        .assertNext(order -> assertEquals("Pizza", order.getName()))
        .verifyComplete();
}

5. @Scheduled: when cron meets the reactive world

@Scheduled tasks run on an ordinary thread pool rather than in a reactive context. In WebFlux this creates an impedance mismatch.

java
// ❌ PROBLEM: @Scheduled is synchronous but your services return Mono
@Scheduled(fixedRate = 60_000)
public void cleanupExpiredSessions() {
    // sessionService returns Mono but @Scheduled is synchronous!

    // Option A: .block() — an anti-pattern, but it works
    sessionService.deleteExpired().block();

    // Option B: .subscribe() — errors are silently swallowed!
    sessionService.deleteExpired().subscribe();
    // If deleteExpired() fails, nobody knows...
}

Worse, a scheduled task has no SecurityContext:

java
// ❌ PROBLEM: A scheduled task has no SecurityContext
@Scheduled(cron = "0 0 2 * * *")
public void generateDailyReport() {
    // ReactiveSecurityContextHolder.getContext() → EMPTY
    // Who are you? There is no authentication.
    reportService.generateAsAdmin().block(); // Kto je "admin"?
}

Calling .subscribe() without waiting for the result creates another problem: overlapping ticks.

java
// ❌ PROBLEM: .subscribe() does not wait for completion
@Scheduled(fixedRate = 30_000)
public void syncInventory() {
    inventoryService.syncAll()
        .subscribe(
            result -> log.info("Synced: {}", result),
            error -> log.error("Sync failed", error)  // Easy to forget
        );
    // The method returns immediately without waiting
    // If the next tick arrives before the previous one finishes → chaos
}

With virtual threads these problems do not arise:

java
// ✅ Virtual Threads: Ordinary @Scheduled, no problems
@Scheduled(fixedRate = 60_000)
public void cleanupExpiredSessions() {
    sessionService.deleteExpired(); // Synchronous, blocking, works
}

@Scheduled(cron = "0 0 2 * * *")
public void generateDailyReport() {
    // Set a system identity for scheduled tasks
    SecurityContextHolder.getContext()
        .setAuthentication(systemAuthentication);
    reportService.generateAsAdmin(); // Works and waits for the result
}

Decision matrix

FactorVirtual threadsWebFlux
CRUD REST API✅ Clear choiceOverkill
Existing MVC app✅ One property❌ Full rewrite
GraphQL queries/mutations✅ SimpleUnnecessary
GraphQL subscriptionsPossible, but unnatural✅ Native
SSE / streamingManual✅ Native backpressure
100k+ WebSocket connectionsPossible✅ More efficient
Spring Security✅ Full supportLimited
Debugging✅ StandardPainful
Team of senior Java developers✅ Productive immediatelyLearning curve
Blocking libraries✅ No problemScheduler workaround
@Scheduled / cron jobs✅ Native.block() or .subscribe()
CPU-bound operations❌ No advantage❌ No advantage

Conclusion: it is not either-or

The best answer to “virtual threads or WebFlux?” is: it depends on the use case.

Choose virtual threads for a conventional business application, an existing Spring MVC stack or a team without reactive programming experience. For 90% of enterprise applications, this is the right choice in 2026.

Choose WebFlux for streaming, GraphQL subscriptions, massive numbers of persistent connections or sophisticated reactive pipelines with backpressure.

And if you have a microservice architecture? Use both. Run CRUD services on virtual threads and streaming or notification services on WebFlux. No rule says the whole platform must use one framework.

All articles