简体   繁体   English

Java 并行流 forEach 完成

[英]Java parallel stream forEach completion

I would like to clarify a behavior of Java parallel streams.我想澄清 Java 并行流的行为。 If I were to use a parallel stream as shown below, can I take it as a guarantee that the line "Should happen at the end" shown in the code below will only print after all parallel tasks have executed?如果我要使用如下所示的并行流,是否可以保证下面代码中显示的“最后应该发生”行只会在所有并行任务执行后才打印?

public static void main(String[] args) {
    Stream.of(1, 2, 3, 5, 7, 8, 9, 10, 11, 23, 399, 939).parallel().forEach(
        integer -> System.out
            .println(Thread.currentThread().getName() + ", for number " + integer));
    System.out.println("Should happen at the end");
}

The repeated trials always print "Should happen at the end" predictably at the end, as shown below.重复试验总是在最后可预测地打印“应该发生在最后”,如下所示。 This maybe happening because main thread is also used to process a few requests.这可能是因为main线程也用于处理一些请求。 Is it possible that in some scenario that main thread is not used and in that case "Should happen at the end" will print before all the ForkJoinPool.commonPool-worker have finished executing their tasks?是否有可能在某些情况下不使用main线程并且在这种情况下“应该在最后发生”将在所有ForkJoinPool.commonPool-worker完成任务之前打印?

main, for number 7
main, for number 6
ForkJoinPool.commonPool-worker-9, for number 3
ForkJoinPool.commonPool-worker-9, for number 4
ForkJoinPool.commonPool-worker-4, for number 1
ForkJoinPool.commonPool-worker-4, for number 10
ForkJoinPool.commonPool-worker-2, for number 2
ForkJoinPool.commonPool-worker-11, for number 5
ForkJoinPool.commonPool-worker-9, for number 8
main, for number 9
Should happen at the end

Stream terminal operations are not asynchronous.终端操作不是异步的。 It means that Java will give back control to the calling thread only after forEach is terminated .这意味着只有在 forEach 终止后,Java 才会将控制权交还给调用线程。 Therefore, what you print after forEach is necessarily printed after in console.因此,您在forEach之后打印的内容必须在控制台之后打印。

Note, however, that if you were to use java.util.Logger API instead of System.out , output ordering would not be as predictable, as logging API itself cannot (for performance reason mainly) guarantee ordering of outputs.但是请注意,如果您要使用java.util.Logger API 而不是System.out ,则输出顺序将无法预测,因为日志记录 API 本身不能(主要出于性能原因)保证输出的顺序。

Further reading on stream operations: Oracle official documentation .进一步阅读流操作: Oracle 官方文档

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

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