Nested classes and lambdas: hidden outer references, effectively final, and which kind to pick
Why a tiny listener keeps a 50 MB object from ever being collected: a closure holds what it uses. Two questions for choosing between static nested, inner, anonymous classes, lambdas and records; why lambdas only read effectively final locals; how to review AI-written callbacks and listeners.
On this page
1. The problem
Each ReportJob holds a 50 MB buffer and registers an event-counting listener on a static event bus. Every job finishes, yet by job 100 a service running -Xmx512m dies with OutOfMemoryError. Heap dump: EventBus.LISTENERS -> OnPriceChanged.this$0 -> ReportJob.
2. Key idea
A callback is a closure: a function carrying the context it uses. As long as whoever holds the closure lives, everything the closure touches lives too, including the enclosing object. The leak here is one forgotten reference.
The four kinds of nested class differ in whether they're tied to an outer instance:
| Kind | Tied to an outer instance | Typical use |
|---|---|---|
| Static nested | No | builders, data-structure nodes, helper DTOs |
| Inner | Yes: the compiler adds a hidden this$0 field |
iterators, views over outer data |
| Anonymous | Yes, in a non-static context | extending abstract classes, multi-method interfaces |
A lambda that uses a field or method of the outer class captures this; one that doesn't, doesn't. Nested records, enums and interfaces are all implicitly static.
2.1 Which kind?
Ask: does it need the enclosing object, and will it outlive that object? If it outlives it, there must be a way to unsubscribe.
| Choice | Use when | Don't use when |
|---|---|---|
| Static nested | a helper type with state that doesn't need the outer | it must read a specific outer instance's state |
| Inner | the helper only makes sense tied to the outer | it gets stored somewhere that outlives the outer |
| Lambda, method reference | one function of a functional interface | it needs its own state or several methods |
| Nested record | immutable data compared by value | objects with changing state |
2.2 Why effectively final?
Go, JavaScript and C# capture the variable itself. Java captures a copy of the value, so a captured local must be effectively final (assigned exactly once). Fields aren't restricted, because the lambda reads them through this.
3. In Java
class ReportJob implements AutoCloseable {
private final byte[] buffer = new byte[50 * 1024 * 1024];
private final AtomicInteger handled = new AtomicInteger();
private Runnable unsubscribe;
// Old bug: inner class OnPriceChanged used an outer field, so it had this$0 -> ReportJob.
// Fix: static nested, given only the counter it needs.
static final class OnPriceChanged implements Consumer<String> {
private final AtomicInteger counter;
OnPriceChanged(AtomicInteger counter) { this.counter = counter; }
@Override public void accept(String event) { counter.incrementAndGet(); }
}
void start() { unsubscribe = EventBus.subscribe(new OnPriceChanged(handled)); }
@Override public void close() { if (unsubscribe != null) unsubscribe.run(); } // always unsubscribe
}Other languages: C# removes handlers with -=; Node.js removeEventListener; Go cancels a context.
Builders, double brace and a few details
- Builders must be static: when you use a builder there's no object to be its outer yet.
HttpCall.to(url).method("POST").build()withBuilderas apublic static final class. - Double brace
new HashMap<>() {{ put("a", 1); }}is an anonymous subclass ofHashMap; sinceHashMapisSerializable, in a non-static method it always keepsthis$0. UseMap.of(...). - Since JDK 18, javac drops
this$0when an inner class doesn't use the outer (exceptSerializableclasses). Don't rely on it: reading one field brings it back. - Local records (Java 16+) are implicitly static, so they can't read the enclosing method's locals or
this; pass values in as components. - Bound method references like
config.prefix()::concatcallconfig.prefix()once at creation; the lambdas -> config.prefix().concat(s)calls it on every run.
4. Working with AI
Delegate to AI: turning anonymous classes into lambdas, inner classes into static nested ones, writing tests that an object is collected (WeakReference + repeated System.gc()).
Check yourself:
- Every listener, scheduled task or callback registered somewhere long-lived has a way out (
close,unsubscribe,cancel). - Nested classes that don't need the outer are
static; builders always are. - No double brace initialization.
- Lambdas handed to executors or caches don't capture
thisby accident.
5. Exercises
Exercise 1: Review "fixed the leak with a lambda"
AI replaced the inner-class listener with a lambda, noting "lambdas don't hold the outer, so the leak is gone". True? Name a test that proves it.
void start() {
EventBus.subscribe(e -> { if (e.startsWith("PRICE")) handled.incrementAndGet(); });
}Solution to Exercise 1
- False: the lambda reads the field
handled, so it capturesthis(ReportJob) and its 50 MB buffer. With nounsubscribe, the static bus holds it forever. - Test: create a job,
start(), keep aWeakReference<ReportJob>, drop the strong reference, callSystem.gc()a few times: the weak reference still holds the object. - Fix: capture a local
AtomicInteger counter = handled;and usee -> counter.incrementAndGet(), and keep the unsubscribe function and call it inclose(). Fixing only the capture still piles listeners up in the bus.
Exercise 2: Read a growing-heap incident
After each deploy, old gen grows ~40 MB/hour and full GCs don't bring it down. Heap dump: 12,000 OrderPoller$1 instances holding 12,000 OrderPollers, rooted in a ScheduledThreadPoolExecutor. Each request creates an OrderPoller that calls scheduler.scheduleAtFixedRate(new Runnable() {...}). Diagnose, act within 15 minutes, fix the root cause.
Solution to Exercise 2
- Diagnosis: the anonymous
Runnableholdsthis$0 -> OrderPoller; the periodic task is never cancelled, so the executor keeps it forever. Each request adds another task. - 15 minutes: restart to reclaim the heap, turn off per-request poller creation with a flag.
- Root fix: one poller (a bean) instead of one per request; keep the
ScheduledFutureandcancel(false)when done. Add a metric for the executor's queued task count.
Summary
- Callbacks keep what they use; inner, anonymous and
this-using lambdas keep the outer. - Callbacks stored somewhere long-lived need a way to unsubscribe.
- Default to static nested; builders always static; immutable data as records.
- Java captures a copy of the value, so locals must be effectively final.
- Don't use double brace initialization.
Further reading: Lambdas and the Stream API.
Practice interview questions on this topic
- What is the difference between static nested, inner, local and anonymous classes?
- What is effectively final, and why can lambdas only use effectively final locals? What does this refer to in a lambda?
- Describe how an inner class or lambda can cause a memory leak in a backend, and how you would find it?
Comments
Community rules