Course contentsShow
← Java
Lesson 1513 of 2,87033. Streams API: Terminal OperationsFree lesson

Common Pitfalls: Non-Associative Operations and Side Effects

Why operations like subtraction fail in parallel, and why side effects in reduce lead to non-deterministic results.

Common Pitfalls: Non-Associative Operations and Side Effects

You'll learn why certain operations break reduce in parallel streams and why modifying external state leads to unpredictable results.

The Problem with Non-Associative Operations

When using reduce, especially in parallel streams, your BinaryOperator must be associative. This means the order of grouping shouldn't matter: (a op b) op c must equal a op (b op c).

Subtraction is NOT associative. Consider reducing [10, 5, 3]:

  • Sequential grouping: ((10 - 5) - 3) = 2
  • Different grouping: (10 - (5 - 3)) = 8

In parallel streams, Java splits your data into chunks, reduces each chunk, then combines results using the combiner. If subtraction is your operator, you get non-deterministic results because chunk boundaries are unpredictable.

// WRONG: subtraction is non-associative
List<Integer> numbers = List.of(10, 5, 3, 2);
int result = numbers.parallelStream()
    .reduce(0, (a, b) -> a - b); // Result varies!

The Danger of Side Effects

Another common mistake is modifying external state inside reduce:

// WRONG: mutating external state
List<Integer> accumulator = new ArrayList<>();
stream.reduce(0, (sum, n) -> {
    accumulator.add(n); // Side effect!
    return sum + n;
});

In parallel streams, multiple threads execute your lambda simultaneously. Without synchronization, this causes race conditions and lost updates. Even in sequential streams, side effects violate the functional paradigm reduce expects.

Key Takeaway: Always use associative operations (addition, multiplication, min, max) in reduce, and never mutate external state—stick to pure functions that only compute and return values.