Video in progress

Strong Middle 🌊 Streams and lambdas

Why does a parallel reduce() sometimes give a wrong result? What requirements apply to the identity and the combiner?

A parallel reduce splits the source into chunks, starts each chunk from the identity and merges the results with the combiner. If the identity isn't truly neutral, the operation isn't associative, or the identity is a mutable object, the result changes with the number of threads.

📖 Answer

There are three requirements, and breaking each one produces its own kind of bug.

  1. The identity must be neutral: combiner(identity, x) == x.
int r = IntStream.rangeClosed(1, 4).parallel().reduce(5, Integer::sum);
// sequential: 15; parallel: 5 is added to every chunk, giving 25, 30 ...
  1. The operation must be associative: (a op b) op c == a op (b op c). Subtraction and computing an average are not:
IntStream.of(10, 3, 2, 1).parallel().reduce(0, (a, b) -> a - b);  // the result is unpredictable

Building an "average" with reduce is the same mistake. The right way is to collect the sum and the count separately (averagingDouble, summaryStatistics).

  1. The identity must be immutable. The most dangerous case:
List<String> all = words.parallelStream()
        .reduce(new ArrayList<>(),
                (list, w) -> { list.add(w); return list; },
                (a, b) -> { a.addAll(b); return a; });

All threads write to a single ArrayList: a race condition and duplicates. reduce is meant for immutable values. Collecting into a mutable container is collect's job, and it creates a new container for each chunk.

The three-argument reduce has one more condition: the combiner must be consistent with the accumulator: combiner(u, accumulator(identity, t)) == accumulator(u, t).

Sequential tests won't catch this kind of bug. For every reduction that uses a parallel stream, I also run the test with .parallel() and on a large data set.