[英]Parallelism and Flatmap in Java 8 Streams
Consider the following example:考虑以下示例:
IntStream.of(-1, 1)
.parallel()
.flatMap(i->IntStream.range(0,1000).parallel())
.forEach(System.out::println);
Does it matter whether I set the inner flag to parallel?我是否将内部标志设置为平行有关系吗? The results look very similar if I leave it away or not.
无论我是否离开它,结果看起来都非常相似。
Also why does the code ( ReferencePipeline
) sequentialize the mapping?另外为什么代码(
ReferencePipeline
)对映射进行顺序化?
I am confused by the line :我对这条线感到困惑:
result.sequential().forEach(downstream);
In the current JDK (jdk1.8.0_25), the answer is no, it doesn't matter you set the inner flag to parallel , because even you set it, the .flatMap () implementation set's back the stream to sequential here:在当前的 JDK (jdk1.8.0_25) 中,答案是否定的,您将内部标志设置为 parallel 并不重要,因为即使您设置了它, .flatMap () 实现也将流设置回顺序这里:
result.sequential().forEach(downstream);
("result" is the inner stream and it's sequential() method's doc says: Returns an equivalent stream that is sequential. May return itself, either because the stream was already sequential, or because the underlying stream state was modified to be sequential.) (“结果”是内部流,它的顺序()方法的文档说:返回一个等效的顺序流。可能会返回自身,因为流已经是顺序的,或者因为底层流状态被修改为顺序。)
In most cases there could be no effort to make the inner stream parallel;在大多数情况下,无需努力使内部流平行; if outer stream has at least same number of items as number of threads that can run parallel (
ForkJoinPool.commonPool().getParallelism() = 3
in my computer).如果外部流的项目数至少与可以并行运行的线程数相同
ForkJoinPool.commonPool().getParallelism() = 3
在我的计算机中为ForkJoinPool.commonPool().getParallelism() = 3
)。
For anyone like me, who has a dire need to parallelize flatMap and needs some practical solution, not only history and theory.对于像我这样迫切需要并行化 flatMap 并需要一些实用解决方案的人来说,不仅仅是历史和理论。
The simplest solution I came up with is to do flattening by hand, basically by replacing it with map + reduce(Stream::concat)
.我想出的最简单的解决方案是手动进行展平,基本上是用
map + reduce(Stream::concat)
替换它。
Already posted an answer with details in another thread: https://stackoverflow.com/a/66386078/3606820已经在另一个线程中发布了详细的答案: https : //stackoverflow.com/a/66386078/3606820
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.