java - publishOn 和并行的区别

标签 java multithreading parallel-processing reactive-programming project-reactor

publishOnparallel 有什么区别?据我了解,publishOn 通过使用几个线程执行操作符链来影响操作符链的进一步处理。但是 parallel 似乎和它的工作原理完全一样。默认情况下,它会创建一个大小为 == #cores 的线程池,并以相同的方式处理运算符的链。还是我遗漏了一些微妙之处?

Schedulers部分状态:

[publishOn] takes signals from upstream and replays them downstream while executing the callback on a worker from the associated Scheduler

和,

a fixed pool of workers that is tuned for parallel work (Schedulers.parallel()). It creates as many workers as you have CPU cores.

因此 publishOn(Schedulers.parallel() 创建尽可能多的线程是核心,并与这些工作人员一起执行链中的后续 operators

然后 Parralel部分状态:

you can use the parallel() operator on any Flux. By itself, this method does not parallelize the work. Rather, it divides the workload into "rails" (by default, as many rails as there are CPU cores).

In order to tell the resulting ParallelFlux where to execute each rail (and, by extension, to execute rails in parallel) you have to use runOn(Scheduler). Note that there is a recommended dedicated Scheduler for parallel work: Schedulers.parallel().

下面两个例子:

Flux.range(1, 10)
    .parallel(2)
    .runOn(Schedulers.parallel())
    .subscribe(i -> System.out.println(Thread.currentThread().getName() + " -> " + i));

Flux.range(1, 10)
    .publishOn(Schedulers.parallel())
    .subscribe(i -> System.out.println(Thread.currentThread().getName() + " -> " + i));

假设计算机有两个核心,以上两个例子是等价的吗?

最佳答案

我有这个问题的答案。

经过一些测试后,我发现 publishOn(Schedulers.parallel() 将在单独的线程上按顺序处理您的 Flux

但是,

使用 parallel().runOn(Schedulers.parallel()) 会将您的 Flux 拆分为您拥有的内核数量,并且每个新的 Flux 将被并行处理。因此,每个新 Fluxes 中的数据可能会按顺序处理,但 Fluxes 一起将是并行处理。

关于java - publishOn 和并行的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45957607/

相关文章:

multithreading - 我怎样才能避免这个循环中的 "i"依赖?语言

multithreading - Rx 调度程序和线程亲和性

parallel-processing - 由于范围,不允许向类中的泛型集合添加值

使用 JsonReader 调用 Java API?

Java 与 Neo4j

java - JSTL 中的 HashMap 键检查

python - 向通过 pool.map 调用的函数添加状态——如何避免酸洗错误

Java 对象转换行为异常

c++ - 将互斥锁引用从 main 传递到类

matlab - 具有多个 CPU 的随机数生成器 Matlab