liveBook · Manning

Associativity

As explained in 100 Java Mistakes and How to Avoid Them

Associativity is the property that the grouping of operands does not change the result of an operation.

Associativity means that regrouping operands does not change an operation’s result: x ⊕ (y ⊕ z) must equal (x ⊕ y) ⊕ z. Stream.reduce requires its accumulator to satisfy this rule, along with an identity value that leaves the other operand unchanged. section 9.5

The sequential-stream trap

A reduction that computes a List hash code with (x, y) -> x * 31 + y can produce the expected result sequentially even though the operation is not associative and 1 is not a valid identity. Replacing stream() with parallelStream() can produce a wrong result because grouping and computation order change. 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 standard List hash-code calculation with the reduction that appears correct sequentially but violates the Stream.reduce contract. section 9.5

Avoid the failure by:

  • Checking both associativity and the identity requirement before passing an accumulator to reduce. section 9.5
  • Treating code that works only on sequential streams as unsafe when parallel execution may occur. section 9.5

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Defines regrouping algebraically and demonstrates the failure through a hash-code reduction, stopping short of general algebraic treatment.
Examples
Uses List.hashCode, a multiplication-and-addition accumulator, and contrasting sequential and parallel computation orders.
What it assumes
Assumes familiarity with Java streams and functions while defining associativity and identity requirements explicitly.
What you can do after
Evaluate reduction accumulators against associativity and identity requirements before using them with streams.
How it connects
Connects associativity with Stream API, reduce, identity elements, sequential streams, and parallel streams.

Also explained in

Compare how 5 books explain associativity →

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.