Project Reactor parallel execution

Mikhail Kadan picture Mikhail Kadan · Mar 26, 2018 · Viewed 11.4k times · Source

Project Reactor 3.1.5.RELEASE

Consider this:

Flux.range(0, 10)
    .publishOn(Schedulers.parallel())
    .subscribe(i -> LOG.info(i));

I am expecting the subscriber to run in multiple threads, but it runs only in one:

2018-03-26 12:30:08.693  INFO 89770 --- [     parallel-1] d.a.Application    : 0
2018-03-26 12:30:08.693  INFO 89770 --- [     parallel-1] d.a.Application    : 1
2018-03-26 12:30:08.693  INFO 89770 --- [     parallel-1] d.a.Application    : 2
2018-03-26 12:30:08.693  INFO 89770 --- [     parallel-1] d.a.Application    : 3
2018-03-26 12:30:08.694  INFO 89770 --- [     parallel-1] d.a.Application    : 4
2018-03-26 12:30:08.694  INFO 89770 --- [     parallel-1] d.a.Application    : 5
2018-03-26 12:30:08.694  INFO 89770 --- [     parallel-1] d.a.Application    : 6
2018-03-26 12:30:08.694  INFO 89770 --- [     parallel-1] d.a.Application    : 7
2018-03-26 12:30:08.694  INFO 89770 --- [     parallel-1] d.a.Application    : 8
2018-03-26 12:30:08.694  INFO 89770 --- [     parallel-1] d.a.Application    : 9

The documentation tells my expectations are correct (http://projectreactor.io/docs/core/release/reference/#threading). Could someone explain to me what's going on there?

Answer

akarnokd picture akarnokd · Mar 26, 2018

Reactive flows are sequential in nature and publishOn just tells the source where to emit each value one after the other. You need to tell the flow to go parallel via parallel, then specify the scheduler via runOn:

Flux.range(0, 10)
.parallel()
.runOn(Schedulers.parallel())
.doOnNext(i -> LOG.info(i))
.sequential()
.subscribe();