如何限制Stream按顺序运行,并阻止它并行运行? [英] How to restrict a Stream to run sequentially, and prevent it from running in parallel?

查看:157
本文介绍了如何限制Stream按顺序运行,并阻止它并行运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法可以返回从自定义spliterator生成的流;分裂器不是安全的。由于分裂器不是踏板安全的,并且它保持状态,我想防止它并行运行。有没有办法阻止返回的流并行运行?

I have a method that returns a stream that is generated from a custom spliterator; the spliterator is not tread safe. Since the spliterator is not tread safe, and it maintains state, I want to prevent it from running in parallel. Is there a way to prevent the returned stream from running in parallel?

我无法找到任何执行此操作的文档或示例。我确实在 BaseStream 类上找到了 sequential()方法,但这似乎并不能阻止用户调用 parallel()来获取并行流。

I have not been able to find any documentation or examples that do this. I did find a sequential() method on the BaseStream class, but that does not appear to prevent a user from then calling parallel() to get a parallel stream.

推荐答案

并行流调用 trySplit()分裂器拆分的方法你的任务到几个部分。返回绝对合法 null 来自 trySplit()说我拒绝拆分。在这种情况下,即使明确调用 .parallel(),也会按顺序执行从spliterator创建的流。

Parallel stream calls trySplit() method of your spliterator to split your task to the several parts. It's absolutely legit to return null from trySplit() saying that "I refuse to split". In this case the stream created from your spliterator will be executed sequentially even if .parallel() was explicitly called.

但是一般情况下,您可以提供至少一个有限的并行性,扩展 AbstractSpliterator 类。它提供默认的 trySplit()实现,它读取一些调用 tryAdvance()方法的输入元素,将它们存储到数组中返回该数组上的分裂器,因此该部分可以单独处理并完全独立于分裂器。这是穷人并行化,但如果下游管道操作耗时,仍然可以提高速度。

However in general you may provide at least a limited parallelism extending the AbstractSpliterator class. It provides default trySplit() implementation which reads some input elements calling your tryAdvance() method, storing them into array and returning the spliterator on that array, so this part can be processed separately and totally independent on your spliterator. This is "poor man" parallelization, but still may improve the speed if the downstream pipeline operations are time consuming.

最后请注意,在大多数情况下,Spliterator实现不应该是线程安全。如果您提供自己的高效 trySplit()实现,则可以保证原始的spliterator和新创建的spliterator将以完全独立的方式处理。因此,如果在拆分后不修改前缀和后缀spliterator中的共享状态,则不应该关心线程安全。

Finally note that in most simple cases Spliterator implementation should not be thread safe. If you provide your own efficient trySplit() implementation, it's guaranteed that the original spliterator and the newly created spliterator will be processed in totally independent manner. So if you don't modify the shared state in prefix and suffix spliterator after splitting, you should not care about thread-safety.

这篇关于如何限制Stream按顺序运行,并阻止它并行运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆