[英]Bug in parallelStream in java
有人可以告诉我为什么会发生这种情况以及这是预期的行为还是错误
List<Integer> a = Arrays.asList(1,1,3,3);
a.parallelStream().filter(Objects::nonNull)
.filter(value -> value > 2)
.reduce(1,Integer::sum)
答案: 10
但是,如果我们使用stream
而不是parallelStream
我得到正确和预期的answer 7
reduce 的第一个参数称为“identity”而不是“initialValue”。
1
是根据加法没有身份。 1
是乘法的恒等式。
尽管如果要对元素求和,则需要提供0
。
Java 使用“identity”而不是“initialValue”,因为这个小技巧可以轻松并行化reduce
。
在并行执行中,每个线程将在 stream 的一部分上运行 reduce,当线程完成时,它们将使用相同的 reduce function 进行组合。
虽然它看起来像这样:
mainThread:
start thread1;
start thread2;
wait till both are finished;
thread1:
return sum(1, 3); // your reduce function applied to a part of the stream
thread2:
return sum(1, 3);
// when thread1 and thread2 are finished:
mainThread:
return sum(sum(1, resultOfThread1), sum(1, resultOfThread2));
= sum(sum(1, 4), sum(1, 4))
= sum(5, 5)
= 10
我希望你能看到,发生了什么以及为什么结果不是你所期望的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.