Video in progress

The profiler shows a high allocation rate and frequent young GCs, and the flame graph has many stream and lambda frames. How do you analyze it, and when do you decide to rewrite the code?

First I find out whether the problem really is the stream or the boxing, intermediate collections and unnecessary objects inside it. JFR or async-profiler's allocation mode shows exactly which line allocates how much. I rewrite only with a measurable goal (p99, GC time) and only on a hot path.

📖 Answer

Having many ReferencePipeline frames in a flame graph is not itself a problem: wherever a stream runs, they'll be there. The question is how much time and memory goes to the stream machinery itself and how much to useful work.

The order of analysis:

  1. Allocation profile: async-profiler -e alloc or JFR's ObjectAllocationSample event. Which types are most common: Integer, Long (boxing), Object[] (toList/ArrayList growth), HashMap$Node (groupingBy), lambda classes.
  2. Context: how many times is this code called per request? Often the problem isn't the stream but a stream inside a loop: for each order a filter().findFirst() over the whole product list, which is O(n×m), and the fix is indexing with a Map.
  3. GC impact: if young GC is fast and cheap (milliseconds), a high allocation rate isn't a problem in itself. I act only if there is an effect on latency or a noticeable share of CPU goes to GC.

Typical fixes, by impact:

// before: an O(n) search plus boxing on every call
products.stream().filter(p -> p.id() == id).findFirst();

// after: index once
Map<Long, Product> byId = products.stream()
        .collect(toMap(Product::id, identity()));
  • Stream<Long> → LongStream;
  • one pipeline instead of intermediate toList()s;
  • if groupingBy is only for counting, counting() or toMap + merge;
  • in very hot loops, a plain for and primitive arrays.

When to stop: if the target metric doesn't improve after the fix, I revert the change. An "optimization" that made the code less readable and didn't help is technical debt.

Important: measure under a prod-like load. A 30% speedup in a local JMH can end up as 0.5% inside the DB wait in prod. That's why I always compare the end-to-end metrics (p99 latency, GC pause, CPU) before and after.