liveBook · Manning

Accumulator

As explained in 100 Java Mistakes and How to Avoid Them

An accumulator function combines two values during a reduction operation to produce another value.

An accumulator combines two values during Stream.reduce. Its operation must be associative and must return the other operand unchanged when given the identity value. section 9.5

Check these requirements before relying on an accumulator:

  • Verify that x ⊕ (y ⊕ z) equals (x ⊕ y) ⊕ z for all operands. section 9.5
  • Verify that combining any value with the identity leaves that value unchanged. section 9.5
  • Do not treat sequential success as proof of correctness: invalid accumulators can fail when computation becomes parallel. section 9.5

A sequentially convincing mistake

A List hash calculation can use reduce(1, (x, y) -> x * 31 + y) and produce the expected result sequentially. The accumulator is nevertheless non-associative and does not have the required identity, so parallelStream() can produce a wrong answer. section 9.5

List<String> list = List.of("a", "b", "c", "d");
System.out.println(list.hashCode());     #1
System.out.println(list.stream()
  .mapToInt(Objects::hashCode)
  .reduce(1, (x, y) -> x * 31 + y));    #2

Compare the direct List hash result with the reduce-based calculation and inspect the accumulator’s hidden contract violation. section 9.5

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains associativity, identity, sequential behavior, and parallel failure, but stops short of general reduction implementation details.
Examples
Uses List.hashCode and a Java reduce expression whose multiplication-based accumulator fails under parallel evaluation.
What it assumes
Assumes familiarity with Java streams and lambda expressions while defining the accumulator contract explicitly.
What you can do after
Evaluate reduction accumulators against identity and associativity requirements before using sequential or parallel streams.
How it connects
Connects accumulators with reduction operations, identity elements, associativity, sequential streams, and parallel streams.

Also explained in

Compare how 4 books explain accumulator →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.