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.

Share

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 main to a synchronous source, the whole pipeline runs on main. A thread change happens only in three ways: an operator that uses time, such as delayElements or timeout; a source that is itself asynchronous, such as an HTTP client calling back from its own thread; or an explicit publishOn or subscribeOn.

Those operators take a Scheduler, Reactor's abstraction over a pool of threads. A scheduler hands out workers, and each worker runs its tasks one at a time, in order. That is why a sequence never sees two of its own signals at the same time even when it changes threads: the Reactive Streams rules require signals to be delivered one after another.

Built-in schedulers
SchedulerThreadsUse for
Schedulers.parallel()One per CPU coreFast, 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 tasksBlocking I/O: JDBC, file access, legacy clients
Schedulers.single()OneWork that must run on one thread in order
Schedulers.immediate()The current threadTests and APIs that require a scheduler
Schedulers.newParallel, newBoundedElastic, fromExecutorServiceAs configuredDedicated 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 to the scheduler name.

publishOn and subscribeOn

The program records which thread runs each step of four small pipelines: none, publishOn in the middle, subscribeOn at the end, and both together with a second subscribeOn.

Java
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:

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
  1. Without a scheduler, everything ran on the thread that subscribed, here main.
  2. publishOn changed the thread for the operators after it. The source still ran on main. Internally publishOn puts the elements in a queue and drains it on a worker, so it costs a hand-over per element.
  3. subscribeOn 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.
  4. With several subscribeOn calls, the one closest to the source won, and the later single() had no effect. publishOn still switched the operators below it to parallel.

Time operators and inner publishers move work too

Thread changes often happen without any publishOn in sight. The program runs time-based operators and a flatMap whose inner publishers use subscribeOn, and records where each step ends up.

Java
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:

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 main, but everything after delayElements ran on parallel. Even the source emitted "b" on parallel, because delayElements requests the next element from its timer thread.
  • Mono.delay and the fallback of timeout also ran on parallel. Most time operators accept a scheduler argument, and delayElements(d, single()) moved the work to single.
  • Each inner Mono.fromCallable ran on a boundedElastic thread, and the map after flatMap ran on whichever thread delivered the result. Code after a flatMap can therefore run on a different thread for every element.
  • publishOn kept the 1,000 elements in their original order. Only flatMap and parallel rails reorder elements.

If code after such an operator must not run on parallel, for example because it blocks, add a publishOn after it.

Splitting CPU work: parallel rails

publishOn moves a sequence to another thread but still processes one element at a time. To use several cores for CPU-heavy work, parallel() splits the sequence into rails, one per core by default, and runOn gives each rail its own worker. The program counts primes below about 300,000 for 8 inputs, three ways, best of 5 runs.

Java
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):

Output
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
  • parallel().runOn(parallel()) created 2 rails on this 2-core machine. The tracking run shows how the work was split: parallel-1 and parallel-2 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.
  • publishOn(parallel()) 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.
  • 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 map, 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.
  • sequential() merged the rails back into a normal Flux, and all three ways computed the same total. Rails do not keep the original order.

Parallel rails are for CPU-bound work. For many independent I/O calls, flatMap with non-blocking clients already runs them concurrently; see Reactor operators.

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 parallel and then on boundedElastic, then calls block() where it must not be called.

Java
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:

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 parallel, 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, because parallel is shared by everything, including all time operators.
  • Wrapped in Mono.fromCallable(...).subscribeOn(Schedulers.boundedElastic()), 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.
  • Calling block() on a parallel thread failed with IllegalStateException, because it could freeze the whole scheduler. The check only fires when block() really has to wait: on an already completed source, such as Mono.just(...).block(), 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 as Thread.sleep or socket reads, during tests.

Dedicated pools and virtual threads

A shared boundedElastic pool is convenient, but one slow dependency can fill it for everyone. The program gives a pretend database its own pool of 2 threads, then wraps an ExecutorService of virtual threads as a scheduler, and finally checks the default boundedElastic when the program is started with -Dreactor.schedulers.defaultBoundedElasticOnVirtualThreads=true.

Java
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:

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 parallel, but now the limit is deliberate and affects only this database. The threads are named after the scheduler, here db-2, which makes thread dumps readable. Custom schedulers own threads, so they must be disposed when no longer needed.
  • Schedulers.fromExecutorService turned a virtual-thread executor into a scheduler. All eight calls ran at once, each on a virtual thread, in about 200 ms.
  • With the system property set, the default boundedElastic itself used virtual threads, named loomBoundedElastic. This option exists since Reactor 3.6 and needs Java 21. Blocking calls then cost far less memory per waiting call; see virtual 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 ThreadLocal. Once a pipeline changes threads, that data is gone. The program sets a request ID in a ThreadLocal, crosses to boundedElastic, and compares it with Reactor's Context.

Java
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:

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 publishOn, the ThreadLocal was null: the value belongs to main, and the map ran on another thread.
  • The Context written with contextWrite belongs to the subscription, so deferContextual read "req-42" on the boundedElastic thread.
  • The Context flows from the subscriber up towards the source, so contextWrite reaches only the operators above it. The step above saw "set-below", and the step below saw nothing. Put contextWrite at the end of the chain, where the subscriber is. Spring and Micrometer provide context propagation to copy such values into ThreadLocals automatically.

Choosing a scheduler

Which scheduler or operator for which job
SituationUse
Non-blocking workNo 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 othersIts own Schedulers.newBoundedElastic(...), disposed on shutdown
Many blocking calls on Java 21 or laterVirtual threads via the system property or fromExecutorService
CPU-heavy work on several coresparallel().runOn(Schedulers.parallel()), then sequential()
Code after a time operator that must not run on parallelpublishOn after it
Per-request dataReactor Context with contextWrite, not ThreadLocal
Waiting for a resultblock() only in main, tests and other non-reactive threads

Testing code that uses time and schedulers is covered on the Reactor testing page, including how to make hours of virtual time pass in milliseconds.