Video in progress

Strong Middle 🌊 Streams and lambdas

How do you debug a bug in a long stream chain, and how do you read the stack trace?

The stack trace has many ReferencePipeline and Spliterator lines: skip them and find the lambda$... line in your own class. IntelliJ's Stream Trace (Java Stream Debugger) mode shows how elements changed at each stage, and pulling complex lambdas out into named methods makes debugging easier.

📖 Answer

A typical stack trace:

java.lang.NullPointerException: Cannot invoke "String.trim()" because ... is null
    at com.shop.ImportService.lambda$parse$2(ImportService.java:48)
    at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197)
    at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:179)
    at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1625)
    ...
    at com.shop.ImportService.parse(ImportService.java:45)

How to read it: the topmost line from your own class (lambda$parse$2, line 48) is where the bug is, in exactly that lambda. The java.util.stream lines are the framework, so don't look at them. The helpful NPE message in Java 14+ also tells you which expression was null.

Additional techniques:

  • Pull the lambda out into a method. With .map(this::parseLine), parseLine shows up in the stack trace, and it's easy to put a breakpoint on it and write a unit test.
  • In IntelliJ, stop on the stream line and use "Trace Current Stream Chain": a table shows which element passed through each stage and which one dropped out at filter.
  • peek(e -> log.debug("after filter: {}", e)) is for a quick check; remove it afterward.
  • Split lines inside a lambda. If you have .map(x -> x.a().b().c()) on one line, it's hard to tell which call the NPE is in; splitting each step into its own map helps.

In a parallel stream the error happens on another thread, and ForkJoinWorkerThread shows up in the stack trace. While debugging, an easy way is to switch to .sequential() and reproduce it.