Reactor schedulers and threading
Reactor does not create threads by itself: operators run on whatever thread delivers the signal. Schedulers and the publishOn and subscribeOn operators decide which threads those are. This page shows which thread runs each step, how time operators and flatMap move work between threads, how to split CPU work, how to call blocking code safely, and why ThreadLocal values disappear on the way.
Contents
How Reactor uses threads
Reactor is concurrency-agnostic: an operator runs on the thread that delivers the signal to it. If you subscribe from mainmaindelayElementstimeoutpublishOnsubscribeOn
Those operators take a Scheduler
| Scheduler | Threads | Use for |
|---|---|---|
Schedulers.parallel() | One per CPU core | Fast, non-blocking CPU work; the default for time operators |
Schedulers.boundedElastic() | Grows on demand up to 10 times the cores, each with a queue of up to 100,000 tasks | Blocking I/O: JDBC, file access, legacy clients |
Schedulers.single() | One | Work that must run on one thread in order |
Schedulers.immediate() | The current thread | Tests and APIs that require a scheduler |
Schedulers.newParallelnewBoundedElasticfromExecutorService | As configured | Dedicated pools, for example one per database |
The programs ran with Reactor 3.7 on JDK 21, on a machine with 2 CPU cores. Thread names are shortened from, say, parallel-3
publishOn and subscribeOn
The program records which thread runs each step of four small pipelines: none, publishOnsubscribeOnsubscribeOn
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import reactor.core.publisher.Flux;
import reactor.core.scheduler.Schedulers;
public class PublishOnSubscribeOn {
static final List<String> LOG = Collections.synchronizedList(new ArrayList<>());
static String thread() {
String name = Thread.currentThread().getName();
return name.replaceAll("-\\d+$", ""); // "parallel-3" -> "parallel"
}
static void step(String what) {
LOG.add(what + " on " + thread());
}
static void show(String title) {
System.out.println(title);
LOG.forEach(l -> System.out.println(" " + l));
LOG.clear();
}
public static void main(String[] args) {
Flux.just(1).doOnNext(n -> step("source")).map(n -> { step("map"); return n; })
.blockLast();
show("no scheduler:");
Flux.just(1)
.doOnNext(n -> step("source"))
.publishOn(Schedulers.parallel()) // everything BELOW moves threads
.map(n -> { step("map after publishOn"); return n; })
.blockLast();
show("publishOn(parallel):");
Flux.just(1)
.doOnNext(n -> step("source"))
.map(n -> { step("map"); return n; })
.subscribeOn(Schedulers.boundedElastic()) // the whole chain from the source
.blockLast();
show("subscribeOn(boundedElastic), placed at the end:");
Flux.just(1)
.doOnNext(n -> step("source"))
.subscribeOn(Schedulers.boundedElastic())
.publishOn(Schedulers.parallel())
.map(n -> { step("map"); return n; })
.subscribeOn(Schedulers.single()) // ignored: the first subscribeOn wins
.blockLast();
show("both, plus a second subscribeOn:");
}
}
Output:
no scheduler:
source on main
map on main
publishOn(parallel):
source on main
map after publishOn on parallel
subscribeOn(boundedElastic), placed at the end:
source on boundedElastic
map on boundedElastic
both, plus a second subscribeOn:
source on boundedElastic
map on parallel
- Without a scheduler, everything ran on the thread that subscribed, here
.main changed the thread for the operators after it. The source still ran onpublishOn . Internallymain puts the elements in a queue and drains it on a worker, so it costs a hand-over per element.publishOn changed the thread on which the subscription starts, so it moved the source and everything that follows, no matter where in the chain it is written.subscribeOn- With several
calls, the one closest to the source won, and the latersubscribeOn had no effect.single() still switched the operators below it topublishOn .parallel
Time operators and inner publishers move work too
Thread changes often happen without any publishOnflatMapsubscribeOn
import java.time.Duration;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
public class TimeAndHops {
static String thread() {
return Thread.currentThread().getName().replaceAll("-\\d+$", "");
}
public static void main(String[] args) {
// Time operators emit from the parallel scheduler, so everything after them moves too
List<String> log = new CopyOnWriteArrayList<>();
Flux.just("a", "b")
.doOnNext(s -> log.add(s + ": source on " + thread()))
.delayElements(Duration.ofMillis(10))
.doOnNext(s -> log.add(s + ": after delayElements on " + thread()))
.blockLast();
log.forEach(System.out::println);
System.out.println("Mono.delay emits on: "
+ Mono.delay(Duration.ofMillis(10)).map(x -> thread()).block());
System.out.println("timeout fallback runs on: " + Mono.never()
.timeout(Duration.ofMillis(10), Mono.fromSupplier(TimeAndHops::thread)).block());
// A time operator can be told to use another scheduler
System.out.println("delayElements(d, single()) emits on: " + Flux.just(1)
.delayElements(Duration.ofMillis(10), Schedulers.single())
.map(x -> thread()).blockLast());
// Inner publishers with their own subscribeOn: results come back on their threads
List<String> inner = Flux.range(1, 4)
.flatMap(i -> Mono.fromCallable(() -> i + " on " + thread())
.subscribeOn(Schedulers.boundedElastic()))
.map(s -> s + ", seen by map on " + thread())
.collectList().block();
inner.stream().sorted().forEach(System.out::println);
// publishOn keeps the order of elements; it only moves them to one worker
System.out.println("publishOn keeps order: " + Flux.range(1, 1000)
.publishOn(Schedulers.parallel())
.collectList().block().equals(Flux.range(1, 1000).collectList().block()));
}
}
Output:
a: source on main
a: after delayElements on parallel
b: source on parallel
b: after delayElements on parallel
Mono.delay emits on: parallel
timeout fallback runs on: parallel
delayElements(d, single()) emits on: single
1 on boundedElastic, seen by map on boundedElastic
2 on boundedElastic, seen by map on boundedElastic
3 on boundedElastic, seen by map on boundedElastic
4 on boundedElastic, seen by map on boundedElastic
publishOn keeps order: true
- "a" left the source on
, but everything aftermain ran ondelayElements . Even the source emitted "b" onparallel , becauseparallel requests the next element from its timer thread.delayElements and the fallback ofMono.delay also ran ontimeout . Most time operators accept a scheduler argument, andparallel moved the work todelayElements(d, single()) .single- Each inner
ran on aMono.fromCallable thread, and theboundedElastic aftermap ran on whichever thread delivered the result. Code after aflatMap can therefore run on a different thread for every element.flatMap kept the 1,000 elements in their original order. OnlypublishOn andflatMap rails reorder elements.parallel
If code after such an operator must not run on parallelpublishOn
Splitting CPU work: parallel rails
publishOnparallel()runOn
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import reactor.core.publisher.Flux;
import reactor.core.scheduler.Schedulers;
public class ParallelRails {
// CPU-bound work: count primes below n the slow way
static int primesBelow(int n) {
int count = 0;
for (int i = 2; i < n; i++) {
boolean prime = true;
for (int d = 2; (long) d * d <= i; d++) {
if (i % d == 0) {
prime = false;
break;
}
}
if (prime) {
count++;
}
}
return count;
}
static final AtomicInteger RUNNING = new AtomicInteger();
static final AtomicInteger MAX_RUNNING = new AtomicInteger();
static final Map<String, Integer> THREADS = new ConcurrentHashMap<>();
// The same work, recording which threads run it and how many at once
static int tracked(int n) {
THREADS.merge(Thread.currentThread().getName(), 1, Integer::sum);
MAX_RUNNING.accumulateAndGet(RUNNING.incrementAndGet(), Math::max);
try {
return primesBelow(n);
} finally {
RUNNING.decrementAndGet();
}
}
static long time(Runnable r) {
long best = Long.MAX_VALUE;
for (int i = 0; i < 5; i++) {
long t0 = System.nanoTime();
r.run();
best = Math.min(best, System.nanoTime() - t0);
}
return best / 1000000;
}
public static void main(String[] args) {
Flux<Integer> jobs = Flux.range(1, 8).map(i -> 300000 + i);
int cores = Runtime.getRuntime().availableProcessors();
System.out.println(cores + " CPU cores, 8 CPU-bound jobs, best of 5 runs");
jobs.map(ParallelRails::primesBelow).blockLast(); // warm-up
long sequential = time(() -> jobs.map(ParallelRails::primesBelow)
.reduce(0, Integer::sum).block());
long rails = time(() -> jobs.parallel().runOn(Schedulers.parallel())
.map(ParallelRails::primesBelow)
.sequential().reduce(0, Integer::sum).block());
long publishOnOnly = time(() -> jobs.publishOn(Schedulers.parallel())
.map(ParallelRails::primesBelow).reduce(0, Integer::sum).block());
System.out.printf("map on one thread: %4d ms%n", sequential);
System.out.printf("parallel().runOn(parallel()): %4d ms%n", rails);
System.out.printf("publishOn(parallel()) then map: %4d ms%n", publishOnOnly);
System.out.println("same total each way: " + jobs.map(ParallelRails::primesBelow)
.reduce(0, Integer::sum).block().equals(jobs.parallel().runOn(Schedulers.parallel())
.map(ParallelRails::primesBelow).sequential().reduce(0, Integer::sum).block()));
System.out.println("rails: " + jobs.parallel().parallelism());
for (String label : new String[] {"parallel rails", "publishOn"}) {
THREADS.clear();
MAX_RUNNING.set(0);
Flux<Integer> work = label.equals("publishOn")
? jobs.publishOn(Schedulers.parallel()).map(ParallelRails::tracked)
: jobs.parallel().runOn(Schedulers.parallel()).map(ParallelRails::tracked)
.sequential();
work.blockLast();
System.out.println(label + ": jobs per thread " + new TreeMap<>(THREADS)
+ ", at most " + MAX_RUNNING.get() + " running at the same moment");
}
}
}
Output (rough comparison on a 2-CPU Linux VM; absolute times will differ on yours):
2 CPU cores, 8 CPU-bound jobs, best of 5 runs
map on one thread: 160 ms
parallel().runOn(parallel()): 83 ms
publishOn(parallel()) then map: 162 ms
same total each way: true
rails: 2
parallel rails: jobs per thread {parallel-1=4, parallel-2=4}, at most 2 running at the same moment
publishOn: jobs per thread {parallel-2=8}, at most 1 running at the same moment
created 2 rails on this 2-core machine. The tracking run shows how the work was split:parallel().runOn(parallel()) andparallel-1 ran 4 of the 8 jobs each, with 2 jobs running at the same moment. Elements are dealt to the rails in turn, so equal jobs give an even split.parallel-2 moved all 8 jobs to a single thread, one job at a time: moving work to another thread is not the same as using two.publishOn(parallel())- Whether two rails also cut the wall time depends on whether a second core is free. In the run shown, the rails took 83 ms against 160 ms for the single-threaded
, about half. The machine is shared with other programs, and in runs where the second core was busy the gain shrank or disappeared: rails can only use cores that are free.map merged the rails back into a normalsequential() , and all three ways computed the same total. Rails do not keep the original order.Flux
Parallel rails are for CPU-bound work. For many independent I/O calls, flatMap
Blocking calls
Reactive code assumes no step blocks its thread. When one does, it occupies a thread that should be serving many other requests. The program runs eight 200 ms blocking lookups first on parallelboundedElasticblock()
import java.time.Duration;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
public class BlockingCalls {
// A blocking call, such as JDBC or a legacy HTTP client
static String legacyLookup(int id) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return "row" + id;
}
static long time(Flux<String> flux) {
long t0 = System.nanoTime();
flux.blockLast();
return Math.round((System.nanoTime() - t0) / 1e8) * 100;
}
public static void main(String[] args) {
int cores = Runtime.getRuntime().availableProcessors();
System.out.println("CPU cores: " + cores + ", parallel scheduler threads: " + cores);
// Wrong: blocking inside a pipeline on the parallel scheduler occupies its few threads
long onParallel = time(Flux.range(1, 8)
.flatMap(id -> Mono.fromCallable(() -> legacyLookup(id))
.subscribeOn(Schedulers.parallel())));
System.out.println("8 blocking calls on parallel: ~" + onParallel + " ms");
// Right: wrap the blocking call and run it on boundedElastic
long onElastic = time(Flux.range(1, 8)
.flatMap(id -> Mono.fromCallable(() -> legacyLookup(id))
.subscribeOn(Schedulers.boundedElastic())));
System.out.println("8 blocking calls on boundedElastic: ~" + onElastic + " ms");
// Reactor can detect block() on a non-blocking thread
try {
String r = Mono.delay(Duration.ofMillis(10))
.map(x -> Mono.delay(Duration.ofMillis(10)).block()) // on a parallel thread
.map(Object::toString)
.block();
System.out.println("no error, got " + r);
} catch (RuntimeException e) {
System.out.println("block() on a parallel thread: " + e.getClass().getSimpleName()
+ ": " + e.getMessage());
}
}
}
Output:
CPU cores: 2, parallel scheduler threads: 2
8 blocking calls on parallel: ~900 ms
8 blocking calls on boundedElastic: ~200 ms
block() on a parallel thread: IllegalStateException: block()/blockFirst()/blockLast() are blocking, which is not supported in thread parallel-1
- On
, only 2 threads exist, so the eight calls ran two at a time: four rounds of 200 ms. Every other reactive task in the application would have waited too, becauseparallel is shared by everything, including all time operators.parallel - Wrapped in
, all eight ran at once on separate threads and finished in one round of about 200 ms. This is the standard recipe for calling blocking code from a reactive pipeline.Mono.fromCallable(...).subscribeOn(Schedulers.boundedElastic()) - Calling
on ablock() thread failed withparallel , because it could freeze the whole scheduler. The check only fires whenIllegalStateException really has to wait: on an already completed source, such asblock() , it returns at once, so such code hides the mistake until a real asynchronous source replaces it. The BlockHound agent detects other blocking calls, such asMono.just(...).block() or socket reads, during tests.Thread.sleep
Dedicated pools and virtual threads
A shared boundedElasticExecutorServiceboundedElastic-Dreactor.schedulers.defaultBoundedElasticOnVirtualThreads=true
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Scheduler;
import reactor.core.scheduler.Schedulers;
public class CustomSchedulers {
static String blockingCall(int id) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return "row" + id;
}
static long time(Scheduler s) {
long t0 = System.nanoTime();
Flux.range(1, 8).flatMap(id -> Mono.fromCallable(() -> blockingCall(id)).subscribeOn(s))
.blockLast();
return Math.round((System.nanoTime() - t0) / 1e8) * 100;
}
public static void main(String[] args) {
// A dedicated, small pool: 2 threads, so 8 calls take 4 rounds
Scheduler db = Schedulers.newBoundedElastic(2, 100, "db");
System.out.println("newBoundedElastic(2 threads): ~" + time(db) + " ms");
System.out.println(" thread name: " + Mono.fromCallable(() -> Thread.currentThread()
.getName()).subscribeOn(db).block());
db.dispose(); // custom schedulers must be disposed
// Any ExecutorService can become a Scheduler, here one virtual thread per task
ExecutorService vt = Executors.newVirtualThreadPerTaskExecutor();
Scheduler virtual = Schedulers.fromExecutorService(vt, "vt");
System.out.println("fromExecutorService(virtual threads): ~" + time(virtual) + " ms");
System.out.println(" is a virtual thread: " + Mono.fromCallable(() -> Thread
.currentThread().isVirtual()).subscribeOn(virtual).block());
virtual.dispose();
vt.shutdown();
// The default boundedElastic can run on virtual threads (Reactor 3.6+, Java 21+)
System.out.println("default boundedElastic, with the system property set: "
+ Mono.fromCallable(() -> Thread.currentThread().isVirtual() + " ("
+ Thread.currentThread().getName() + ")")
.subscribeOn(Schedulers.boundedElastic()).block());
}
}
Output:
newBoundedElastic(2 threads): ~900 ms
thread name: db-2
fromExecutorService(virtual threads): ~200 ms
is a virtual thread: true
default boundedElastic, with the system property set: true (loomBoundedElastic-1)
- With 2 threads, the eight 200 ms calls ran in four rounds, as on
, but now the limit is deliberate and affects only this database. The threads are named after the scheduler, hereparallel , which makes thread dumps readable. Custom schedulers own threads, so they must be disposed when no longer needed.db-2 turned a virtual-thread executor into a scheduler. All eight calls ran at once, each on a virtual thread, in about 200 ms.Schedulers.fromExecutorService- With the system property set, the default
itself used virtual threads, namedboundedElastic . This option exists since Reactor 3.6 and needs Java 21. Blocking calls then cost far less memory per waiting call; seeloomBoundedElasticvirtual threads .
ThreadLocal values do not follow the pipeline
Many libraries keep per-request data, such as a request ID, a security principal or a transaction, in a ThreadLocalThreadLocalboundedElasticContext
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
public class ThreadLocalTrap {
static final ThreadLocal<String> REQUEST_ID = new ThreadLocal<>();
public static void main(String[] args) {
REQUEST_ID.set("req-42"); // set by a web filter, say
String seen = Mono.just("work")
.publishOn(Schedulers.boundedElastic())
.map(w -> w + " sees request id " + REQUEST_ID.get())
.block();
System.out.println("ThreadLocal after publishOn: " + seen);
// Reactor's Context travels with the subscription, not with the thread
String withContext = Mono.just("work")
.publishOn(Schedulers.boundedElastic())
.flatMap(w -> Mono.deferContextual(ctx -> Mono.just(w + " sees request id "
+ ctx.get("requestId") + " on "
+ Thread.currentThread().getName().replaceAll("-\\d+$", ""))))
.contextWrite(ctx -> ctx.put("requestId", "req-42")) // written at the bottom
.block();
System.out.println("Context after publishOn: " + withContext);
// contextWrite only reaches operators above it
String below = Mono.deferContextual(ctx -> Mono.just(ctx.getOrDefault("requestId",
"(none)")))
.contextWrite(ctx -> ctx.put("requestId", "set-below"))
.flatMap(v -> Mono.deferContextual(ctx -> Mono.just(v + " / "
+ ctx.getOrDefault("requestId", "(none)"))))
.block();
System.out.println("above / below contextWrite: " + below);
}
}
Output:
ThreadLocal after publishOn: work sees request id null
Context after publishOn: work sees request id req-42 on boundedElastic
above / below contextWrite: set-below / (none)
- After
, thepublishOn wasThreadLocal : the value belongs tonull , and themain ran on another thread.map - The
written withContext belongs to the subscription, socontextWrite read "req-42" on thedeferContextual thread.boundedElastic - The
flows from the subscriber up towards the source, soContext reaches only the operators above it. The step above saw "set-below", and the step below saw nothing. PutcontextWrite at the end of the chain, where the subscriber is. Spring and Micrometer provide context propagation to copy such values intocontextWrite s automatically.ThreadLocal
Choosing a scheduler
| Situation | Use |
|---|---|
| Non-blocking work | No scheduler at all; let it run where the signal arrives |
| A blocking call (JDBC, files, legacy client) | Mono.fromCallable(...).subscribeOn(Schedulers.boundedElastic()) |
| A slow dependency that must not starve others | Its own Schedulers.newBoundedElastic(...) |
| Many blocking calls on Java 21 or later | Virtual threads via the system property or fromExecutorService |
| CPU-heavy work on several cores | parallel().runOn(Schedulers.parallel())sequential() |
Code after a time operator that must not run on parallel | publishOn |
| Per-request data | Reactor ContextcontextWriteThreadLocal |
| Waiting for a result | block()main |
Testing code that uses time and schedulers is covered on the