简体   繁体   English

定义了parallelStream终止吗?

[英]is parallelStream termination well defined?

I find I struggle slightly with the consistency guarantees offered by the parallel streams: 我发现我在并行流提供的一致性保证方面有些挣扎:

1. myList.parallelStream().map(mymapper).forEach(myFn)
2. // Is myFn guaranteed to be called for each element in myList here ?

In other words, can I be sure that all the forkJoinTasks that will execute myFn are completed at line 2 ? 换句话说,我可以确定所有将执行myFn的forkJoinTasks在第二行完成吗?

Yes. 是。 The parallel tasks within a complete stream pipeline are executed synchonously. 完整的流管道中的并行任务是同步执行的。 Line 2 will be executed only after all the tasks have completed. 仅在所有任务完成后才执行第2行。

The package documentation for java.util.stream states, 有关java.util.stream软件包说明,

In almost all cases, terminal operations are eager, completing their traversal of the data source and processing of the pipeline before returning. 在几乎所有情况下,终端操作人员都很渴望在返回之前完成对数据源的遍历和对管道的处理。

Note however that any side effects accomplished by the forEach tasks might not be visible to other threads. 但是请注意,由forEach任务完成的任何副作用对于其他线程可能都不可见。 In practice, forEach can only operate by having its action perform side effects. 实际上, forEach只能通过使其动作执行副作用来进行操作。 As mentioned in the Stream.forEach javadoc , the action must use proper synchronization or other constructs in order to ensure thread-safe operation and proper visibility of side effects. Stream.forEach javadoc中所述,该操作必须使用适当的同步或其他构造,以确保线程安全操作和适当的副作用可见性。

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

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