Virtual Threads and Spring WebFlux – Spring-boot

by
Alexei Petrov
performance reactive-programming spring-boot spring-webflux virtual-threads

Quick Fix: Utilize the boundedElastic scheduler in project-reactor 3.5.11 for blocking operations to prevent IllegalStateException. Keep an eye on the integration progress between Project Reactor and Project Loom at https://github.com/reactor/reactor-core/issues/3084 for future dedicated Scheduler.

The Problem:

In Spring WebFlux, can incorporating virtual threads provide a performance advantage over standard Spring Boot, and under what circumstances? Also, provide a code example that utilizes virtual threads in Spring WebFlux and explain its benefits.

The Solutions:

Solution 1: Using Bounded Elastic Scheduler

Since the current version of Project Reactor (3.5.11) and Spring WebFlux doesn’t fully support virtual threads, you can still utilize bounded elastic scheduler for blocking operations. Here’s an updated version of your code:

private final Scheduler scheduler = Schedulers.boundedElastic();

public Mono<String> myMethod() {
    return Mono.fromFuture(CompletableFuture.supplyAsync(() -> doBlockOperation(), scheduler));
}

In this example, we use the Schedulers.boundedElastic() method to create a bounded elastic scheduler. This scheduler will automatically create and manage a pool of threads for executing blocking operations. When a blocking operation is submitted to the scheduler, it will be executed in one of the threads from the pool. Once the operation is complete, the thread will be returned to the pool and can be used to execute other blocking operations.

This approach allows you to take advantage of virtual threads while still ensuring that blocking operations are executed in a non-blocking manner. However, it’s important to note that using a bounded elastic scheduler may not provide the same performance benefits as using virtual threads directly.

Q&A

Is there any point to use virtual threads in Spring WebFlux?

Virtual threads are not currently supported for Spring WebFlux.

When can we expect virtual threads for Spring WebFlux?

Video Explanation:

The following video, titled "Will Virtual Threads render Spring WebFlux Obsolete? - YouTube", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

This video provides further insights and detailed explanations related to the content discussed in the article.