Is Java-8's DoubleStream.sum() method stable when run in parallel? Is Java-8's DoubleStream.sum() method stable when run in parallel? multithreading multithreading

Is Java-8's DoubleStream.sum() method stable when run in parallel?


I think the documentation of DoubleStream::sum is pretty clear about this issue:

[..] The value of a floating-point sum is a function both of the input values as well as the order of addition operations. The order of addition operations of this method is intentionally not defined to allow for implementation flexibility to improve the speed and accuracy of the computed result. [..]

That means, you shouldn't rely on stability, in particular not for parallel streams.


On the other hand, it's not surprising, that you see the same results for each run. Conceptually, the sum method might be implemented as follows:

double sum(double[] array, int startInclusive, int endExclusive) {    int distance = endExclusive - startInclusive;    if (distance < 1000) {        double total = 0;        for (int i = startInclusive; i < endExclusive; ++i) {            total += array[i];        }        return total;    } else {        int middle = startInclusive + distance / 2;        var left = async sum(array, startInclusive, middle);        var right = async sum(array, middle, endExclusive);        return await left + await right;    }}

Although the scheduling of the asynchronously executed tasks is nondeterminstic, the method always returns the same result, because the order of addition operations is the same (i.e. the parentheses are not rearranged).

However, a more sophisticated implementation might consider the current work load as well as the expected execution time of sub-tasks (in comparison with the costs of asynchronous operations). If that happens, the results might vary.


I do get different results from what you posted for the parallel summation, so I can confirm that it is not stable in all circumstances. The serial summation appears to behave the same in your test and in my test. My JVM may be different from yours, and I may have a different number of cores than you have. Anyway, here are the results I obtained for the same iterations that you posted results for.

Oracle CorporationJava HotSpot(TM) 64-Bit Server VM25.51-b03-----Min: -1.89188, Max: 1.90414, Average: 0.0541140Serial difference:   -2.66454e-15Parallel difference: -2.66454e-15-----Min: 0.000113827, Max: 3.99513, Average: 1.17402Serial difference:   1.70530e-13Parallel difference: 1.70530e-13-----Min: -7.95673, Max: 7.87757, Average: 0.0658356Serial difference:   0.00000Parallel difference: 3.55271e-15-----Min: 2.53794e-09, Max: 15.8122, Average: 2.96504Serial difference:   -4.54747e-13Parallel difference: -4.54747e-13