Sub topic 14
Threading, Schedulers, and keeping the event loop free
This chapter assumes you know how the WebFlux event loop works, can build Mono and Flux pipelines with operators, and understand why a thread-per-request model blocks. Here you will learn where reactive code runs, how a blocking call stalls the server, and how to move that call onto a safe thread.
Few threads, so no blocking
WebFlux on Netty handles requests with a small number of event-loop threads, usually one per CPU core. Each thread serves many connections. That only works if no handler holds a thread while it waits.
A blocking call is any call that parks the thread until a result arrives. Examples are JDBC queries, Thread.sleep, synchronous HTTP clients, and file I/O. If a handler makes one on an event-loop thread, every other request assigned to that thread waits too. With four event-loop threads, four slow calls can freeze the whole server.
Where does a pipeline run?
Reactor does not create threads on its own. A pipeline runs on the thread that calls subscribe, and each operator continues on whichever thread signalled the previous one. In WebFlux, the framework subscribes for you on an event-loop thread. Your operators then run there.
A Scheduler is Reactor's abstraction for choosing where work runs. The common ones are:
| Scheduler | Threads | Use it for |
|---|---|---|
| `Schedulers.parallel()` | One per CPU core | Short, CPU-bound work |
| `Schedulers.boundedElastic()` | Capped pool that grows with load | Blocking calls |
| `Schedulers.single()` | One reusable thread | Work that must run in order |
| `Schedulers.immediate()` | The current thread | Opting out of switching |
Moving a blocking call with subscribeOn
Wrap the blocking call in Mono.fromCallable, then use subscribeOn to run the subscription on boundedElastic.
Mono<Report> report = Mono
.fromCallable(() -> legacyClient.fetchReport(id)) // blocking call
.subscribeOn(Schedulers.boundedElastic());The callable runs on a boundedElastic thread. The event-loop thread is released right away, so it can serve other requests. When the report is ready, the result flows downstream.
subscribeOn and publishOn
These two operators both change threads, but at different points.
subscribeOnsets the thread for the subscription and the source. Its position in the chain does not matter, because it affects the pipeline from the start.publishOnswitches the thread for everything below it. Its position matters.
import reactor.core.publisher.Flux;
import reactor.core.scheduler.Schedulers;
public class ThreadDemo {
public static void main(String[] args) throws InterruptedException {
Flux.just(1, 2, 3)
.map(n -> {
System.out.println("map on " + Thread.currentThread().getName());
return n * 10;
})
.publishOn(Schedulers.parallel())
.map(n -> {
System.out.println("second map on " + Thread.currentThread().getName());
return n + 1;
})
.subscribe(n -> System.out.println("got " + n));
Thread.sleep(500); // keep main alive for the async work
}
}The first map runs on main. The second map and the subscriber run on a parallel thread. Use publishOn when only part of a pipeline needs a different thread, such as a CPU-heavy step after an I/O step.
Finding blocking calls
Blocking calls are easy to write by accident. Two habits help:
- Review every library call in a pipeline and ask whether it waits on I/O. Choose reactive clients (WebClient, reactive repositories) where they exist.
- Use BlockHound in tests. It is a Java agent that throws an error when blocking code runs on a non-blocking thread. It also catches blocking inside libraries you did not write.
Avoid calling block() inside a WebFlux handler. Reactor throws an exception if you call it on an event-loop thread, and it defeats the purpose where it is allowed.
boundedElastic is a safety valve, not a goal. If most of your calls block, a servlet stack may fit better than WebFlux.
Exercise
A handler calls a JDBC repository inside flatMap and the server becomes slow under load, even though CPU use is low. What is the likely cause, and how can you contain it?
Show answer
The JDBC call blocks an event-loop thread, so few threads are left to serve other requests. Wrap the call in Mono.fromCallable and add subscribeOn(Schedulers.boundedElastic()), or switch to a reactive driver such as R2DBC.
Exercise
In a chain, you put publishOn(Schedulers.parallel()) after a map and before a second map. Which map runs on the parallel thread?
Show answer
The second one. publishOn changes the thread only for operators below it, so the first map stays on the original thread.