简体   繁体   English

带有过滤器链接的 ParallelStream

[英]ParallelStream with filter chaining

Does filter chaining change the outcome if i use parallelStream() instead of stream() ?如果我使用parallelStream()而不是stream()filter链接会改变结果吗?

I tried with a few thousand records, and the output appeared consistent over a few iterations.我尝试了几千条记录,并且 output 在几次迭代中显得一致。 But since this involves threads,(and I could not find enough relevant material that talks about this combination) I want to make doubly sure that parallel stream does not impact the output of filter chaining in any way.但由于这涉及线程,(我找不到足够的相关材料来讨论这种组合)我想加倍确保并行 stream 不会以任何方式影响过滤器链接的 output。 Example code:示例代码:

List<Element> list = myList.parallelStream()
      .filter(element -> element.getId() > 10)
      .filter(element -> element.getName().contains("something"))
      .collect(Collectors.toList());

Short answer: No .简短的回答:

The filter operation as documented expects a non-interferening and stateless predicate to apply to each element to determine if it should be included as part of the new stream.文档中的filter操作期望对每个元素应用无干扰无状态的谓词,以确定是否应将其作为新 stream 的一部分包含在内。

Few aspects that you shall consider for that are -您应该考虑的几个方面是 -

  1. With an exception to concurrent collections(what do you choose as myList in the existing code to be) -除了并发集合(你在现有代码中选择什么作为myList ) -

For most data sources, preventing interference means ensuring that the data source is not modified at all during the execution of the stream pipeline.对于大多数数据源而言,防止干扰意味着确保在 stream 管道的执行过程中完全不修改数据源。

  1. The state of the data sources ( myList and its element s within your filter operations are not mutated)数据源的 state (过滤器操作中的myList及其element未发生突变)

Note also that attempting to access mutable state from behavioral parameters presents you with a bad choice with respect to safety and performance;另请注意,尝试从行为参数访问可变的 state 会给您带来安全和性能方面的错误选择;

Moreover, think around it, what is it in your filter operation that would be impacted by multiple threads.此外,请考虑一下,您的filter操作中会受到多线程影响的内容是什么。 Given the current code, nothing functionally, as long as both the operations are executed, you would get a consistent result regardless of the thread(s) executing them.鉴于当前代码,没有任何功能,只要执行这两个操作,无论执行它们的线程如何,您都会得到一致的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM