Video in progress
How can lambdas cause a memory leak? How do you find such a case in prod?
A lambda written inside an instance method can hold on to this (and through it the whole object graph). If such a lambda is put in a long-lived place (a static listener list, a cache, a scheduler), the object is never garbage collected. You find it in a heap dump by looking at the path to the GC root.
📖 Answer
A typical example:
class ReportScreen {
private final byte[] bigBuffer = new byte[50_000_000];
void open(EventBus bus) {
bus.subscribe(event -> refresh(event)); // this is captured
}
void refresh(Event e) { ... }
}
refresh is an instance method, so the lambda captures this. EventBus is global, and the subscription is never cancelled. Every ReportScreen that was opened, together with its 50 MB buffer, stays in memory.
The hard part: that the lambda is capturing this isn't visible in the code. refresh(event) means this.refresh(event). Even accessing a field (threshold) captures this, because the field is this.threshold.
Other sources:
- a large object inside
ThreadLocal.withInitial(() -> ...); - a lambda handed to
ScheduledExecutorService.scheduleAtFixedRate, if it isn'tcancelled; - a context closed over in the value of a
Caffeine/ConcurrentHashMap.computeIfAbsent; - a method reference:
bus.subscribe(this::refresh)is the same thing.
How I find it:
- In Grafana/JFR, old gen keeps growing even after GC.
- I take a dump with
jcmd <pid> GC.heap_dumpand open the dominator tree in Eclipse MAT. - For the suspicious object, "Path to GC Roots": if the path shows a synthetic class like
ReportScreen$$Lambda/0x..., the lambda is what's holding it.
The fix: cancel the subscription (return a Subscription and unsubscribe in close()), a weak reference (WeakReference) if needed, or pass the lambda only the value it needs in a local variable, so this isn't captured.
Sign up to mark studied questions and save your progress.