gpt4 book ai didi

Java8流顺序和并行执行产生不同的结果?

转载 作者:IT老高 更新时间:2023-10-28 20:33:40 25 4
gpt4 key购买 nike

在 Java8 中运行以下流示例:

    System.out.println(Stream
.of("a", "b", "c", "d", "e", "f")
.reduce("", (s1, s2) -> s1 + "/" + s2)
);

产量:

/a/b/c/d/e/f

这 - 当然 - 不足为奇。由于http://docs.oracle.com/javase/8/docs/api/index.html?overview-summary.html流是顺序执行还是并行执行都无关紧要:

Except for operations identified as explicitly nondeterministic, such as findAny(), whether a stream executes sequentially or in parallel should not change the result of the computation.

AFAIK reduce() 是确定性的,而 (s1, s2) -> s1 + "/"+ s2 是关联的,因此添加 parallel() 应该产生相同的结果:

    System.out.println(Stream
.of("a", "b", "c", "d", "e", "f")
.parallel()
.reduce("", (s1, s2) -> s1 + "/" + s2)
);

但是我机器上的结果是:

/a//b//c//d//e//f

这里有什么问题?

顺便说一句:使用(首选).collect(Collectors.joining("/")) 而不是 reduce(...) 产生相同的结果 a/b/c/d/e/f 用于顺序和并行执行。

JVM 详细信息:

java.specification.version: 1.8
java.version: 1.8.0_31
java.vm.version: 25.31-b07
java.runtime.version: 1.8.0_31-b13

最佳答案

来自reduce的文档:

The identity value must be an identity for the accumulator function. This means that for all t, accumulator.apply(identity, t) is equal to t.

在你的情况下这不是真的 - ""和 "a"创建了 "/a"。

我提取了累加器函数并添加了一个打印输出来显示发生了什么:

BinaryOperator<String> accumulator = (s1, s2) -> {
System.out.println("joining \"" + s1 + "\" and \"" + s2 + "\"");
return s1 + "/" + s2;
};
System.out.println(Stream
.of("a", "b", "c", "d", "e", "f")
.parallel()
.reduce("", accumulator)
);

这是示例输出(运行之间会有所不同):

joining "" and "d"
joining "" and "f"
joining "" and "b"
joining "" and "a"
joining "" and "c"
joining "" and "e"
joining "/b" and "/c"
joining "/e" and "/f"
joining "/a" and "/b//c"
joining "/d" and "/e//f"
joining "/a//b//c" and "/d//e//f"
/a//b//c//d//e//f

您可以在函数中添加一个 if 语句来分别处理空字符串:

System.out.println(Stream
.of("a", "b", "c", "d", "e", "f")
.parallel()
.reduce((s1, s2) -> s1.isEmpty()? s2 : s1 + "/" + s2)
);

正如 Marko Topolnik 所注意到的,检查 s2 不是必需的,因为累加器不一定是可交换函数。

关于Java8流顺序和并行执行产生不同的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28724850/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com