Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
798 views
in Technique[技术] by (71.8m points)

project reactor - ParallelFlux vs flatMap() for a Blocking I/O task

I have a Project Reactor chain which includes a blocking task (a network call, we need to wait for response). I'd like to run multiple blocking tasks concurrently.

It seems like either ParallelFlux or flatMap() could be used, bare-bone examples:

Flux.just(1)
    .repeat(10)
    .parallel(3)
    .runOn(Schedulers.elastic())
    .doOnNext(i -> blockingTask())
    .sequential()
    .subscribe()

or

Flux.just(1)
    .repeat(10)
    .flatMap(i -> Mono.fromCallable(() -> {blockingTask(); return i;}).subscribeOn(Schedulers.elastic()), 3)
    .subscribe();

What are the merits of the two techniques? Is one to be preferred over the other? Are there any alternatives?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

parallel is tailored for parallelization of tasks for performance purposes, and dispatching of work between "rails" or "groups", each of which get their own execution context from the Scheduler you pass to runOn. In short, it will put all your CPU cores to work if you do CPU intensive work. But you're doing I/O bound work...

So in your case, flatMap is a better candidate. That use of flatMap for parallelization is more about orchestration.

These are pretty much the 2 alternatives, if you don't count the slightly different flavor of flatMap that flatMapSequential is (concatMap doesn't really allow for parallelization).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...