Video in progress
If several elements throw exceptions inside a parallel stream, what does the caller see, and what happens to the work on the other threads?
Only one exception reaches the calling thread; the others are usually lost. The other workers don't stop immediately: they may finish the elements they've already started, so side effects end up partially executed. In the stack trace you can also see that the error came from a different thread.
📖 Answer
List<Receipt> receipts = orders.parallelStream()
.map(o -> {
paymentGateway.charge(o); // a side effect!
return receiptService.build(o); // throws for some of them
})
.toList();
Say build fails for 3 out of 1000 orders. What happens:
toList()ends with an exception: you see one error, and from the message you may not be able to tell which order it was.- The other two errors vanish silently.
- The other threads may have kept working on their chunks. That is, some of the orders were charged, but no result came back. Which ones is unknown.
On a sequential stream the side effect is also partially executed, but at least the order is clear: the ones before the error were processed. In parallel there's no such boundary.
About the stack trace: the error occurs on a ForkJoinPool.commonPool-worker-N thread. When the JDK rethrows it to the caller, it sometimes creates a new instance of the exception and sets the original as its cause, so read the getCause() chain to the end.
What I do:
- I don't put side-effecting work into a parallel stream: it's only for pure computation.
- If I need the errors too, I don't throw: I return the result as a value (a
Result/Either-style record) and separate them at the end, so every error is visible. - I add the element ID to the message:
throw new ReceiptException(o.id(), e).
Sign up to mark studied questions and save your progress.