Scrivio Interview library
DebuggingIntermediate7 min read · updated 12 November 2026

This code returns different totals on each run when the stream is parallel:

Java
BigDecimal total = list.parallelStream().reduce(BigDecimal.ZERO, (a, b) -> a.add(b).setScale(2, RoundingMode.HALF_UP), BigDecimal::add);

What is wrong?

The accumulator rounds to two decimal places after every addition, but the combiner adds chunk totals without rounding, so the function is no longer associative and the accumulator and combiner disagree. The total then depends on how the parallel stream happened to split the list. The fix is to add the exact values and round once at the end: list.parallelStream().reduce(BigDecimal.ZERO, BigDecimal::add).setScale(2, RoundingMode.HALF_UP).

Background to this question

Totals that change depending on how the code runs are among the most alarming bugs in financial software, because they look random and they erode trust in every other number. This question is popular because the code looks careful: it uses BigDecimal, it names a rounding mode, it even provides a combiner. The bug is in the mathematics of the reduction, not in any single line. In this answer, we will recap the contract that reduce expects, reproduce the drift with a small list, see exactly where the rounding breaks associativity and the accumulator-combiner rule, apply the fix, and look at the same problem with double.

1A Quick Recap of the reduce Contract

The three-argument reduce(identity, accumulator, combiner) works like this on a parallel stream. The list is split into chunks. Each chunk starts from the identity and folds in its elements with the accumulator. Then the chunk results are merged pairwise with the combiner. How many chunks there are, and where they start and end, depends on the list size and on the number of threads in the common pool.

For the result to be the same however the work is split, three things must hold. The identity must change nothing. The operation must be associative, meaning the grouping of the steps does not matter. And the accumulator and combiner must agree: combiner(u, accumulator(identity, t)) must equal accumulator(u, t). In words, folding an element in directly must give the same result as reducing it alone and merging it in.

2Reproducing the Drift

Two values are enough to see the problem. One is a charge of half a cent and the other a refund of half a cent, which is common once tax or currency conversion produces fractions.

Java
List<BigDecimal> list = List.of(new BigDecimal("0.005"), new BigDecimal("-0.005"));
BinaryOperator<BigDecimal> combiner = BigDecimal::add;
BiFunction<BigDecimal, BigDecimal, BigDecimal> acc =
(a, b) -> a.add(b).setScale(2, RoundingMode.HALF_UP);
// Sequential: one chunk, the accumulator sees both values in turn
BigDecimal s1 = acc.apply(BigDecimal.ZERO, list.get(0)); // 0.005 -> 0.01
BigDecimal seq = acc.apply(s1, list.get(1)); // 0.01 - 0.005 = 0.005 -> 0.01
// Parallel: two chunks, each starts from ZERO, then the combiner merges them
BigDecimal c1 = acc.apply(BigDecimal.ZERO, list.get(0)); // 0.01
BigDecimal c2 = acc.apply(BigDecimal.ZERO, list.get(1)); // -0.005 -> -0.01 (HALF_UP rounds away from zero)
BigDecimal par = combiner.apply(c1, c2); // 0.00
// The exact sum, rounded once
BigDecimal exact = list.get(0).add(list.get(1)).setScale(2, RoundingMode.HALF_UP); // 0.00

Notice that the same two numbers give 0.01 in one grouping and 0.00 in the other. With thousands of values, the number of chunks and their boundaries decide which values get rounded on their own and which get rounded together with a running total. Change the list size, the machine's core count or the pool's parallelism and the split changes, so the total changes with it. That is what the team sees as different totals on each run.

3Where the Code Breaks the Rules

The first problem is associativity. Rounding after each step means the result depends on the order in which partial sums are formed. The sequential path computed round(round(0 + 0.005) - 0.005), while the parallel path computed round(0.005) + round(-0.005). Those are different groupings, and with rounding in the middle they give different answers.

The second problem is that the combiner does not do what the accumulator does. Plug our example into the rule: combiner(u, accumulator(ZERO, t)) with u = 0.01 and t = -0.005 is 0.01 + (-0.01) = 0.00, while accumulator(u, t) is round(0.005) = 0.01. The rule fails, so the library is allowed to give either answer, and it does. Adding a setScale call to the combiner would not save it: the grouping problem from rounding in the middle remains.

Same values, different groupings
PathStepsResult
Sequential, one chunkround(round(0 + 0.005) + (-0.005))0.01
Parallel, two chunksround(0.005) + round(-0.005)0.00
Exact sum, rounded onceround(0.005 + (-0.005))0.00
Rounding inside the accumulator makes the answer depend on how the stream splits.

4The Fix: Sum Exactly, Round Once

BigDecimal addition is exact. It never loses a digit, so it is truly associative, and BigDecimal.ZERO is a true identity. If we keep the reduction exact and apply the business rounding once to the final total, every split gives the same answer.

Java
BigDecimal total = list.parallelStream()
.reduce(BigDecimal.ZERO, BigDecimal::add) // exact: 0.000
.setScale(2, RoundingMode.HALF_UP); // 0.00, the same on every run
// Equivalent, and fine for most list sizes:
BigDecimal total2 = list.stream()
.reduce(BigDecimal.ZERO, BigDecimal::add)
.setScale(2, RoundingMode.HALF_UP); // 0.00

Notice that the two-argument form is enough here, because the result type is the same as the element type and the accumulator and combiner are the same function. That removes the second way to get it wrong.

There is one business question to raise. Sometimes the rules really do require rounding each line first, for example when each invoice line is printed rounded and the total must equal the sum of the printed lines. In that case we round each element in a map step, before the reduction, and then add exactly: map(v -> v.setScale(2, RoundingMode.HALF_UP)).reduce(BigDecimal.ZERO, BigDecimal::add). Each element is rounded once, independently of any split, so the result is stable again. What we must never do is round running totals, because which values share a running total depends on the split.

5The Same Problem With double

Floating-point addition is not associative either. Each addition rounds to the nearest representable binary value, so (a + b) + c and a + (b + c) can differ in the last bits. A parallel sum of doubles can therefore differ slightly between runs and between sequential and parallel execution.

Java
double x = (0.1 + 0.2) + 0.3; // 0.6000000000000001
double y = 0.1 + (0.2 + 0.3); // 0.6

DoubleStream.sum and Collectors.summingDouble reduce this error with compensated summation, a technique that tracks the small error lost at each step and adds it back. That makes the result much more accurate, but it does not make doubles suitable for money. For amounts we use BigDecimal or a long count of minor units such as cents, and both of those add exactly.

6Follow-up questions

Would making the stream sequential fix the bug?

It would make the result repeatable, but still wrong. The sequential path rounds every running total, so it gave 0.01 for a set of values whose exact sum is 0.00. Hiding the drift by removing parallel would leave a systematic rounding error in every total. The fix is to stop rounding in the middle.

How can I catch this kind of mistake in tests?

Run the same reduction sequentially and in parallel on many random inputs, including negative values and values with more decimals than the target scale, and assert that the results match and equal the exact sum rounded once. A property-based test library such as jqwik makes this easy, but a simple loop with a fixed random seed already catches it.

Is the parallel stream even worth it for summing BigDecimals?

Usually not. Adding a few thousand BigDecimals takes microseconds, and the cost of splitting and coordinating threads is larger than the work. Unless profiling shows that this sum is a real hot spot over millions of values, a sequential stream is simpler and avoids the shared common pool.

7Conclusion

In this answer, we saw that rounding inside the accumulator turns an exact, associative BigDecimal addition into an operation whose result depends on grouping, and that a combiner which does not round breaks the rule that combiner(u, accumulator(identity, t)) equals accumulator(u, t). Because a parallel stream decides the grouping from the size of the list and the pool, the total drifts between runs and machines. The fix is to add exact values with BigDecimal::add and round once at the end, or round each element in a map step if the business rules require it. Doubles have the same associativity problem, which compensated summation reduces but does not make them fit for money.

What to say in the interviewAbout 80 seconds aloud

Open with

The problem is the setScale inside the accumulator. BigDecimal addition on its own is exact and associative, but once I round each running total, the result depends on how the additions are grouped.

Then, if they want more

A parallel stream splits the list into chunks based on its size and the pool's parallelism, accumulates each chunk from ZERO with the rounding accumulator, and then merges the chunks with BigDecimal::add, which does not round at all.

So the accumulator and combiner also disagree: the rule says combiner of u and accumulator of identity and t must equal accumulator of u and t, and here it does not. A tiny example: 0.005 and minus 0.005. Sequentially I get round of 0.005, which is 0.01, then round of 0.01 minus 0.005, which is 0.01 again.

Split into two chunks I get 0.01 plus minus 0.01, which is 0.00. The fix is to sum exactly and round once: reduce(BigDecimal.ZERO, BigDecimal::add) and then setScale(2, HALF_UP) on the result. If the business wants each line rounded, I round each element in a map before the reduce, never the running total.

Doubles have the same issue, because floating-point addition is not associative; summingDouble uses compensated summation to reduce the error, but for money I would use BigDecimal or long cents anyway.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "This code returns different totals on each run when the stream is parallel:": https://scrivio-interview-library.netlify.app/java/streams/e7c265c92d/