Sub topic 14
Threading, Schedulers, and keeping the event loop free
This chapter assumes you can read a Reactor pipeline (map, flatMap, switchIfEmpty) and have written an annotated WebFlux controller. You should also know that Netty serves requests on a small, fixed set of event-loop threads, as covered earlier in this tutorial. Here you will learn which threads your code actually runs on, how to move work between them, and how to find and fix calls that stall the event loop.
Who runs your code?
Reactor does not manage threads on its own. A pipeline runs on whichever thread subscribes to it, and each signal (onNext, onComplete) is delivered on the thread that produced it. In WebFlux on Reactor Netty, that thread is usually an event-loop thread. These threads are named like reactor-http-nio-3, and by default there are max(CPU cores, 4) of them.
An event-loop thread serves many connections. While your code runs on it, no other request assigned to that thread makes progress. A handler that blocks for 200 ms on a 4-thread loop can freeze a quarter of your capacity for that time. Under load, latency rises for every client, even though CPU usage looks low.
The rule is simple. Code on an event-loop thread must either finish quickly or return a publisher that completes later. It must never wait.
What counts as blocking
- JDBC calls and other blocking database drivers
Thread.sleep,Future.get,CountDownLatch.await- Blocking HTTP clients such as
RestTemplateor a legacy SDK - Synchronous file I/O on large files
Mono.block()andFlux.blockFirst()/blockLast()inside a pipeline- Long CPU-bound loops (not blocking in the I/O sense, but they occupy the thread just the same)
Reactor refuses some of this at runtime. Calling block() on a thread marked non-blocking throws IllegalStateException with a message like block()/blockFirst()/blockLast() are blocking, which is not supported in thread reactor-http-nio-2. Other blocking calls, such as Thread.sleep or a JDBC query, give no warning.
The built-in Schedulers
A Scheduler is Reactor's abstraction over a thread or pool of threads. You get the standard ones from the Schedulers factory class.
| Factory method | Threads | Use it for |
|---|---|---|
| `Schedulers.parallel()` | Fixed, one per CPU core | Short CPU-bound work. Never block on it. |
| `Schedulers.boundedElastic()` | Grows on demand to 10 × cores by default, with a task queue | Blocking calls such as JDBC or legacy clients |
| `Schedulers.single()` | One reusable thread | Work that must be serialized |
| `Schedulers.immediate()` | The calling thread | Opting out of thread switching |
| `Schedulers.fromExecutorService(...)` | Your own executor | Pools you must size or name yourself |
boundedElastic is the one you will use most often in a web service. Its cap on threads and queued tasks means a slow dependency leads to rejected tasks, not an unbounded number of threads.
subscribeOn and publishOn
Two operators move work between Schedulers, and they affect different parts of the pipeline.
subscribeOn(scheduler)chooses the thread where the subscription, and therefore the source, runs. Its position in the chain does not matter, because it affects the whole chain upstream of the subscriber.publishOn(scheduler)switches the thread for everything after it. Position matters. Operators above it keep their previous thread.
This program prints the thread name at each step so you can see both operators at work. Running blockLast() in main is fine because main is not an event-loop thread.
import reactor.core.publisher.Flux;
import reactor.core.scheduler.Schedulers;
public class ThreadDemo {
static void log(String step, Object value) {
System.out.println(Thread.currentThread().getName()
+ " | " + step + " | " + value);
}
public static void main(String[] args) {
Flux.range(1, 2)
.doOnNext(n -> log("source", n))
.publishOn(Schedulers.parallel())
.map(n -> n * 10)
.doOnNext(n -> log("after publishOn", n))
.subscribeOn(Schedulers.boundedElastic())
.blockLast();
}
}The source lines print a boundedElastic-N thread, because subscribeOn moved the subscription there. The after publishOn lines print a parallel-N thread. The exact numbers vary between runs.
Fixing a blocking call
Suppose your service depends on a synchronous client you cannot replace yet. This controller blocks the event loop:
@GetMapping("/reports/{id}")
public Mono<Report> report(@PathVariable String id) {
Report r = legacyClient.fetchReport(id); // blocks the event-loop thread
return Mono.just(r);
}The call runs while the method is still assembling the pipeline, on the event-loop thread. Wrapping the call in a lazy Mono and subscribing on boundedElastic moves it off:
@GetMapping("/reports/{id}")
public Mono<Report> report(@PathVariable String id) {
return Mono
.fromCallable(() -> legacyClient.fetchReport(id)) // blocking call
.subscribeOn(Schedulers.boundedElastic());
}fromCallable defers the call until subscription, and subscribeOn makes that subscription happen on a worker thread. If the callable throws, the Mono signals an error instead of propagating the exception into the framework. If it returns null, the Mono completes empty, so combine it with switchIfEmpty when you need a 404.
This does not make the call non-blocking. A boundedElastic thread is still tied up while it waits. You have protected the event loop, but the blocking work still costs one thread per concurrent call, and the pool is capped. Treat it as a bridge until a non-blocking client is available.
Offloading inside a flatMap
When you call a blocking function once per element, put the offloading inside flatMap. If you put subscribeOn outside it, the whole chain moves to one worker thread and the calls run one after another.
Flux<Report> reports = Flux.fromIterable(ids)
.flatMap(id -> Mono
.fromCallable(() -> legacyClient.fetchReport(id))
.subscribeOn(Schedulers.boundedElastic()),
4); // at most 4 calls in flightThe second argument to flatMap limits how many inner publishers are subscribed at once. Without it, the default is 256, which could queue a large burst of tasks on boundedElastic.
CPU-heavy work
Hashing a large payload or compressing a response is not blocking I/O, but it still holds an event-loop thread for the whole computation. Move it with publishOn(Schedulers.parallel()) or Mono.fromCallable(...).subscribeOn(Schedulers.parallel()). Keep the parallel scheduler for CPU work only. If a blocking call sneaks onto it, you will have the same problem as on the event loop, with a smaller pool.
Finding blocking calls with BlockHound
Reviewing code by eye misses blocking calls hidden inside libraries. BlockHound is a Java agent that instruments known blocking methods and throws a BlockingOperationError when one is called on a non-blocking thread. Add io.projectreactor.tools:blockhound as a test dependency and install it once in your tests:
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import reactor.blockhound.BlockHound;
import reactor.blockhound.BlockingOperationError;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import java.time.Duration;
class BlockingDetectionTest {
@BeforeAll
static void install() {
BlockHound.install();
}
@Test
void sleepOnNonBlockingThreadIsDetected() {
Mono<Long> blocking = Mono.delay(Duration.ofMillis(1))
.doOnNext(tick -> {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
StepVerifier.create(blocking)
.expectErrorMatches(e -> e instanceof RuntimeException
&& e.getCause() instanceof BlockingOperationError)
.verify();
}
}Mono.delay signals on the parallel scheduler, which Reactor marks as non-blocking, so the Thread.sleep inside doOnNext is caught. On JDK 13 and later, you may need the JVM flag -XX:+AllowRedefinitionToAddDeleteMethods for BlockHound to install.
BlockHound only reports calls that actually run during a test, so run it against tests that exercise your real endpoints.
Gotchas
- Thread-bound state is lost.
ThreadLocalvalues, including logging MDC, do not follow a request across a thread switch. Reactor carries per-subscription data in itsContext. Spring Security's reactive support uses it for the authenticated user. subscribeOnplacement is misleading. It looks like it applies only to what follows, but it applies to the subscription. If a pipeline has several, the one closest to the source wins for the source.- Switching threads has a cost. Do not add
publishOnafter every operator. Switch once, at the point where you need to. - Rejected tasks. If
boundedElasticfills its queue, it rejects new tasks and the pipeline signals an error. This is by design. It is better than silent unbounded growth, but you should size timeouts and concurrency limits so that you rarely get there. - Mixed stacks. Putting a blocking JDBC repository behind WebFlux leads to many threads parked on
boundedElastic. If most of your calls block, a servlet stack may serve you better.
Exercise
A WebFlux handler calls jdbcTemplate.queryForObject(...) directly and returns the result wrapped in Mono.just(...). Under load, unrelated endpoints that do no database work also become slow. Explain why, and rewrite the call so it no longer stalls the event loop.
Show answer
The JDBC call is blocking and runs on a Netty event-loop thread while the handler method executes. Each such call holds one of the few event-loop threads, so requests to every other endpoint served by that thread wait. Rewrite it as Mono.fromCallable(() -> jdbcTemplate.queryForObject(sql, mapper, id)).subscribeOn(Schedulers.boundedElastic()). fromCallable defers the call until subscription, and subscribeOn runs it on a boundedElastic worker thread, so the event loop stays free. The worker thread is still blocked while the query runs, so the real fix is a non-blocking driver such as R2DBC.
Exercise
In the pipeline Flux.range(1, 3).map(f).publishOn(Schedulers.parallel()).map(g).subscribeOn(Schedulers.boundedElastic()), which scheduler runs f and which runs g?
Show answer
f runs on boundedElastic, because subscribeOn moves the subscription and source, and operators before any publishOn keep that thread. g runs on parallel, because publishOn switches the thread for everything after it.