Schedulers and threads

Senior Frequently asked 6 min

On this page

The question

What is the difference between publishOn and subscribeOn?

30-second answer

subscribeOn sets the thread on which the subscription travels up and the source starts, so it affects the whole chain, wherever you write it. publishOn switches thread for the elements travelling down, so it only affects the operators after it. Without either, everything runs on the thread that subscribed. Reactor is concurrency-agnostic: it does not create threads unless asked to.

Understand it

Operators coloured by the thread that runs them

Step by step

With no scheduler, Reactor stays on the thread that subscribed. Every step runs on main, and nothing here is asynchronous.

Step 1 of 6
View as text

A chain of operators, one row each, in the order of the code. Each row names and colors the thread that ran it: main, boundedElastic-1 or parallel-1. Scheduler operators have no thread of their own and are marked with a switch or a start.

With no scheduler, Reactor stays on the thread that subscribed. Every step runs on main, and nothing here is asynchronous.

subscribeOn sets where the subscription starts, so the source runs there. It affects the whole chain, and its position in the chain makes no difference.

publishOn switches thread for everything after it. Above it, the source and the first map stay on main.

Together: subscribeOn picks the thread for the source and everything up to publishOn, and publishOn takes over from there.

With two subscribeOn calls, the one closest to the source wins. The second has no visible effect on the elements.

Each publishOn switches again, so one chain can hop threads several times. The last switch decides where the subscriber runs.

A chain of operators, one row each, in the order of the code. Each row names and colors the thread that ran it: main, boundedElastic-1 or parallel-1. Scheduler operators have no thread of their own and are marked with a switch or a start.

With no scheduler, Reactor stays on the thread that subscribed. Every step runs on main, and nothing here is asynchronous.

subscribeOn sets where the subscription starts, so the source runs there. It affects the whole chain, and its position in the chain makes no difference.

publishOn switches thread for everything after it. Above it, the source and the first map stay on main.

Together: subscribeOn picks the thread for the source and everything up to publishOn, and publishOn takes over from there.

With two subscribeOn calls, the one closest to the source wins. The second has no visible effect on the elements.

Each publishOn switches again, so one chain can hop threads several times. The last switch decides where the subscriber runs.

Takeaway: subscribeOn chooses where the source starts, wherever you write it. publishOn switches thread for what comes after it, right where you write it.

A blocking call on the event loop

Predict

A WebFlux server runs with one event loop thread. Its handler calls Thread.sleep(500). Two requests arrive at the same moment.

When does the second response finish?
View as text

The handler code above a timeline from 0 to 1,000 ms, with one bar per request. A WebFlux server runs with one event loop thread. Its handler calls Thread.sleep(500). Two requests arrive at the same moment. The learner first predicts when the second response finishes.

The event loop is stuck in the first sleep, so the second request only starts at 500 ms and ends near 1,000 ms. Measured: 1,069 ms. The bars run one after the other.

Any other request on that thread waits too. A trivial /ping took 344 ms during the sleep, against 4 ms during a non-blocking delay. A second bar shows ping waiting for the sleep to end.

Reactor only catches its own blocking. Calling block() here throws IllegalStateException, and the client gets a 500. Thread.sleep and JDBC raise nothing: they just freeze the thread. The bar ends early in an error.

The fix: wrap the call in fromCallable and move it with subscribeOn(boundedElastic). The sleeps overlap, and /ping answers in 4 ms. The two requests overlap on boundedElastic, and ping passes through.

The handler code above a timeline from 0 to 1,000 ms, with one bar per request. A WebFlux server runs with one event loop thread. Its handler calls Thread.sleep(500). Two requests arrive at the same moment. The learner first predicts when the second response finishes.

The event loop is stuck in the first sleep, so the second request only starts at 500 ms and ends near 1,000 ms. Measured: 1,069 ms. The bars run one after the other.

Any other request on that thread waits too. A trivial /ping took 344 ms during the sleep, against 4 ms during a non-blocking delay. A second bar shows ping waiting for the sleep to end.

Reactor only catches its own blocking. Calling block() here throws IllegalStateException, and the client gets a 500. Thread.sleep and JDBC raise nothing: they just freeze the thread. The bar ends early in an error.

The fix: wrap the call in fromCallable and move it with subscribeOn(boundedElastic). The sleeps overlap, and /ping answers in 4 ms. The two requests overlap on boundedElastic, and ping passes through.

Takeaway: An event loop serves many requests with few threads, so one blocking call stalls them all. Move blocking work to boundedElastic, and never block on a loop thread.

Which scheduler for which work?Fast, non-blocking CPU work belongs on parallel, which has one thread per core. Blocking calls belong on boundedElastic, which has ten threads per core and a queue. Work that must stay in order belongs on single. Nothing blocking may run on an event loop.Work to scheduleCPU, no blocking:parallelBlocking call:boundedElasticOne at a time:singleSocket I/O only:the event loop
Which scheduler for which work?Fast, non-blocking CPU work belongs on parallel, which has one thread per core. Blocking calls belong on boundedElastic, which has ten threads per core and a queue. Work that must stay in order belongs on single. Nothing blocking may run on an event loop.Work to scheduleCPU, no blocking:parallelBlocking call:boundedElasticOne at a time:singleSocket I/O only:the event loop
Which scheduler for which work?

In code

Mono<Order> order = Mono.fromCallable(() -> jdbcTemplate.queryForObject(SQL, mapper, id))
        .subscribeOn(Schedulers.boundedElastic());
Wrap a blocking call, so the event loop stays free
Flux<Thumbnail> thumbnails = images
        .publishOn(Schedulers.parallel())    // what follows runs on parallel
        .map(image -> resize(image));
Move heavy work to another thread pool
Mono<String> greeting = Mono.deferContextual(context -> Mono.just("Hi " + context.get("user")))
        .publishOn(Schedulers.parallel())
        .contextWrite(context -> context.put("user", "ana"));    // read from below
ThreadLocal does not follow a chain, but Context does
Where publishOn and subscribeOn actsubscribeOn acts while the subscribe signal travels up, so it sets the thread for the source wherever it is written. publishOn acts while elements travel down, so it changes the thread only for the operators after it.subscribe() travelsupsubscribeOn:the source startshereElements traveldownpublishOn:a new thread fromhere
Where publishOn and subscribeOn actsubscribeOn acts while the subscribe signal travels up, so it sets the thread for the source wherever it is written. publishOn acts while elements travel down, so it changes the thread only for the operators after it.subscribe() travelsupsubscribeOn:the source startshereElements traveldownpublishOn:a new thread fromhere
Where publishOn and subscribeOn act

Solve it

Name the thread that runs each step

The interviewer shows a chain with one publishOn(parallel()) and two subscribeOn calls, boundedElastic() then single(), and asks which thread runs the source, the map before publishOn, the map after it, and the subscriber.

  1. Start from subscribe(). The subscription travels up the chain. Each subscribeOn moves that trip to its scheduler, so the one closest to the source decides where the source emits: boundedElastic.
  2. Ignore the other subscribeOn. single() only runs the first part of the trip up. The source never emits on it.
  3. Follow the data down. The source and the first map run on boundedElastic. publishOn(parallel()) hands every later signal to a parallel thread.
  4. Finish the chain. The second map and the subscriber run on parallel.
  5. Check. Log Thread.currentThread().getName() in each step, or add .log(): the names match.
Flux.range(1, 3)                                      // emits on boundedElastic-1
    .map(i -> step("A", i))                           // boundedElastic-1
    .publishOn(Schedulers.parallel())
    .map(i -> step("B", i))                           // parallel-1
    .subscribeOn(Schedulers.boundedElastic())         // closest to the source: this one wins
    .subscribeOn(Schedulers.single())                 // no effect on where the source emits
    .subscribe(i -> step("C", i));                    // parallel-1
The answer, step by step

How to answer

  • With two subscribeOn calls, the one closest to the source wins.
  • Each publishOn switches again, so a chain can hop threads.
  • Some operators switch by themselves; Mono.delay continues on parallel.
  • Use subscribeOn to move a blocking source, and publishOn to move later steps.

Common mistakes

  • Thinking that subscribeOn only affects what is written above it.
  • Believing a Flux is asynchronous by itself. Without a scheduler, it runs on the caller's thread.

Follow-up questions

What is boundedElastic, and how does it differ from parallel?

boundedElastic is for blocking work. It grows up to 10 threads per core, removes idle ones, and queues tasks when full, at most 100,000 per thread. parallel is for fast CPU work, with one thread per core, and it rejects blocking: block() throws there. So wrap JDBC (Java Database Connectivity) or legacy calls in fromCallable plus subscribeOn(boundedElastic).

  • On a 32-core machine, the bound was 320 threads and the queue limit 100,000.
  • It keeps blocking calls off event loop threads, which is its whole purpose.
  • It only moves the blocking, so its threads are still a bounded resource.
  • On Java 21, reactor.schedulers.defaultBoundedElasticOnVirtualThreads runs it on virtual threads.

See it in the infographic: Operators coloured by the thread that runs them See it in the infographic: A blocking call on the event loop

What happens if you block in a reactive chain?

It depends on the thread. On an event loop, a blocking call freezes that thread, so every request sharing it waits: with one loop thread, a 500 ms sleep delayed the next request to about 1,000 ms. Nothing warns you. Only Reactor's own block() is detected, throwing IllegalStateException on non-blocking threads. Under load, throughput collapses.

  • Thread.sleep and JDBC raise no error; they just stall the loop.
  • BlockHound detects blocking calls on non-blocking threads, in tests.
  • Fix it with fromCallable and subscribeOn(boundedElastic).
  • Event loop threads are few, one per core by default.

See it in the infographic: A blocking call on the event loop

Why does ThreadLocal not work in a reactive chain, and what replaces it?

One request hops across threads, and one thread serves many requests, so a value set in a ThreadLocal stays behind: after publishOn, reading it gave null. Reactor's Context replaces it. It is an immutable map attached to the subscription: write with contextWrite and read with deferContextual. It propagates from the subscriber upward, so the write goes below the read.

  • This is why SecurityContextHolder and MDC (Mapped Diagnostic Context) need special care in WebFlux.
  • A contextWrite above the reader is invisible to it.
  • A nested subscribe() loses the Context.
  • Micrometer's context propagation can restore ThreadLocals automatically.

See it in the infographic: Operators coloured by the thread that runs them

A Flux was built with delayElements. Which thread runs the next operator?

A parallel thread. Time-based operators such as delayElements, Mono.delay and Flux.interval schedule on Schedulers.parallel by default, so what follows runs there, even though you never wrote publishOn. Most of them have an overload that takes a scheduler.

Does publishOn make operators after it run in parallel?

No. It moves them to another thread, and they still handle one element at a time, in order. For real parallelism, use flatMap with a subscribeOn inside, which handles elements on several threads, or parallel().runOn(...).

Check yourself

1. Which thread runs the source?
Flux.range(1, 3)
    .map(n -> n * 2)
    .subscribeOn(Schedulers.boundedElastic())
    .map(n -> n + 1)
    .subscribe();
Show answers
  • A boundedElastic thread: Correct. subscribeOn applies to the subscription, so its position in the chain does not matter.
  • The thread that called subscribe: Incorrect. That is what would happen with no scheduler, or with only a publishOn after the source.
  • A parallel thread: Incorrect. Nothing here asks for parallel, and map does not change threads.
2. A WebFlux handler calls Thread.sleep(500) on the event loop. What does Reactor do?
Show answers
  • Nothing. The thread freezes, with no error.: Correct. Reactor only detects its own block() methods, so this bug shows up as latency.
  • It throws IllegalStateException.: Incorrect. That is what block() does. A sleep is plain JDK (Java Development Kit) code.
  • It moves the sleep to another thread.: Incorrect. Reactor never moves work on its own. You have to ask with subscribeOn.