简体   繁体   English

java 中的并行流中的错误

[英]Bug in parallelStream in java

Can someone tell me why this is happening and if it's expected behaviour or a bug有人可以告诉我为什么会发生这种情况以及这是预期的行为还是错误

List<Integer> a = Arrays.asList(1,1,3,3);

a.parallelStream().filter(Objects::nonNull)
        .filter(value -> value > 2)
        .reduce(1,Integer::sum)

Answer: 10答案: 10

But if we use stream instead of parallelStream I'm getting the right & expected answer 7但是,如果我们使用stream而不是parallelStream我得到正确和预期answer 7

The first argument to reduce is called "identity" and not "initialValue". reduce 的第一个参数称为“identity”而不是“initialValue”。

1 is no identity according to addition. 1是根据加法没有身份。 1 is identity for multiplication. 1是乘法的恒等式。

Though you need to provide 0 if you want to sum the elements.尽管如果要对元素求和,则需要提供0


Java uses "identity" instead of "initialValue" because this little trick allows to parallelize reduce easily. Java 使用“identity”而不是“initialValue”,因为这个小技巧可以轻松并行化reduce


In parallel execution, each thread will run the reduce on a part of the stream, and when the threads are done, they will be combined using the very same reduce function.在并行执行中,每个线程将在 stream 的一部分上运行 reduce,当线程完成时,它们将使用相同的 reduce function 进行组合。

Though it will look something like this:虽然它看起来像这样:

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

I hope you can see, what happens and why the result is not what you expected.我希望你能看到,发生了什么以及为什么结果不是你所期望的。

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

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