Java parallelStream not showing correct result

This question already has an answer here:

  • How do I write a correct micro-benchmark in Java? 11 answers

  • I think your code having issue with count() method. As parallelStream will try to perform task concurrently. This method should be synchronized or you can make totaleven as Atomtic Integer. Hope it helps.


    Instead of using the forEach to increment a counter you can use the terminal operation Stream:count

    For example

    totaleven = randomList.stream().filter(e -> e % 2 ==0).count();
    totaleven = 0;
    totaleven = randomList.parallelStream().filter(e -> e % 2 ==0).count();
    

    totaleven would need to be changed to data type long or casting applied.


    What's wrong with parallel stream result? If it is too small then most likely you have problem with totaleven++ as it is not thread safe. Use AtomicInteger or any other thread safe solution.

    链接地址: http://www.djcxy.com/p/86550.html

    上一篇: 简单的Java程序在Windows 2008 Server上运行缓慢

    下一篇: Java parallelStream没有显示正确的结果