Sobes.tech
Senior

What are schedulers in Reactor?

sobes.tech AI

Answer from AI

In Reactor (a reactive library for Java), schedulers are responsible for managing the threads on which reactive stream operations are executed.

Main types of schedulers:

  • Schedulers.immediate() — executes tasks in the current thread.
  • Schedulers.single() — uses a single thread for sequential task execution.
  • Schedulers.elastic() — creates a new thread as needed, caches and reuses them, suitable for blocking operations.
  • Schedulers.parallel() — a thread pool optimized for parallel computations.

Using schedulers allows controlling where exactly the code will run, for example, switching from an IO thread to a computation or UI thread.

Example:

Flux.range(1, 5)
    .subscribeOn(Schedulers.parallel()) // data generation in a parallel pool
    .map(i -> i * 2)
    .publishOn(Schedulers.single()) // switch to a single thread for further processing
    .subscribe(System.out::println);

Thus, schedulers help manage asynchrony and parallelism in reactive applications.

What are schedulers in Reactor? — Java - sobes.tech