Sub topic 12
Hidden outer references and memory retention
This chapter assumes you can already write inner, local, and anonymous classes and read Outer.this. It also assumes you know what garbage collection reachability means: an object stays alive while a chain of references leads to it from a GC root, such as a static field or a running thread.
The reference you never wrote
An inner class instance always belongs to an enclosing instance. The compiler stores that link in a hidden field. With javac the field is a synthetic field named this$0 (this$1 for deeper nesting), and the compiler passes the outer object to the constructor as an extra parameter. You never declare or see either of them in source, but they are why count += step works in an inner class without any qualifier.
Which classes carry the hidden field depends on where they are declared:
| Kind of class | Holds an outer instance? |
|---|---|
| Static nested class | No |
| Inner member class | Yes |
| Local class in an instance method | Yes |
| Anonymous class in an instance method or instance initializer | Yes |
| Local or anonymous class in a static method or static initializer | No |
The rule is about context, not about the keyword static on the class. An anonymous class created inside a static method has no enclosing instance, because none exists.
You can check this with reflection. The program below looks for a field whose type is the outer class.
import java.lang.reflect.Field;
public class OuterRefDemo {
private int value = 7;
class Inner {
int read() { return value; }
}
static class Nested { }
Runnable anonInInstance() {
return new Runnable() {
@Override
public void run() { System.out.println(value); }
};
}
static Runnable anonInStatic() {
return new Runnable() {
@Override
public void run() { System.out.println("hi"); }
};
}
static void report(Class<?> c) {
boolean holdsOuter = false;
for (Field f : c.getDeclaredFields()) {
if (f.getType() == OuterRefDemo.class) {
holdsOuter = true;
}
}
System.out.println(c.getName() + " holds outer: " + holdsOuter);
}
public static void main(String[] args) {
report(Inner.class);
report(Nested.class);
report(new OuterRefDemo().anonInInstance().getClass());
report(anonInStatic().getClass());
}
}The output is:
OuterRefDemo$Inner holds outer: true
OuterRefDemo$Nested holds outer: false
OuterRefDemo$1 holds outer: true
OuterRefDemo$2 holds outer: falseHow a hidden reference becomes a leak
A leak happens when something long-lived holds an inner class instance, and that instance holds a much larger outer object that nobody else needs. The chain looks like this:
The code only needed the title string, yet the reachable set includes the whole Screen. The program below shows both versions side by side.
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
public class Screen {
private static final List<Runnable> REGISTRY = new ArrayList<>();
private final byte[] pixels = new byte[1_000_000];
private final String title;
public Screen(String title) { this.title = title; }
// Reads the field "title", so the anonymous class uses Screen.this.
void registerLeaky() {
REGISTRY.add(new Runnable() {
@Override
public void run() { System.out.println("closing " + title); }
});
}
// Copies only what it needs into a static nested class.
void registerLean() {
REGISTRY.add(new Closer(title));
}
private static class Closer implements Runnable {
private final String title;
Closer(String title) { this.title = title; }
@Override
public void run() { System.out.println("closing " + title); }
}
static boolean holdsScreen(Runnable r) {
for (Field f : r.getClass().getDeclaredFields()) {
if (f.getType() == Screen.class) return true;
}
return false;
}
public static void main(String[] args) {
new Screen("a").registerLeaky();
new Screen("b").registerLean();
for (Runnable r : REGISTRY) {
System.out.println(r.getClass().getName() + " keeps a Screen alive: " + holdsScreen(r));
}
}
}The output is:
Screen$1 keeps a Screen alive: true
Screen$Closer keeps a Screen alive: falseScreen "a" can never be collected while its listener stays in REGISTRY, so about one megabyte stays reachable per registration. Screen "b" can be collected as soon as main drops it.
Common ways this shows up
The same pattern appears in several everyday designs:
- Listener and callback registries. An anonymous listener added to a long-lived event source and never removed pins its creator.
- Caches and static collections. Any static
MaporListthat stores inner class instances, or lambdas that usethis, retains their owners. - Executors and threads. A task queued on a long-lived pool holds its outer object until the task finishes. A thread that never ends (a daemon loop, for example) holds it for the life of the process.
- Iterators and views. A non-static inner iterator or sublist view keeps the whole collection alive. This is usually intended, but it surprises people who keep only a small view of a very large structure.
- Double-brace initialization.
new ArrayList<>() {{ add("x"); }}creates an anonymous subclass. If it is created in an instance method, each list holds the enclosing object. It also has a different class fromArrayList, which breaksequalschecks that compare classes. - Serialization. A serializable inner class drags its outer instance into the serialized form. If the outer class is not serializable, you get a
NotSerializableException.
Fixes, from most to least preferred
- Make the class static when it does not need the outer object. This is the default recommendation. A static nested class makes the dependency visible, because it must receive everything it uses through its constructor. IDEs and linters often flag inner classes that never use their outer instance.
- Copy the data you need into a local variable or constructor argument. Capturing a local does not capture
this. Remember that on JDK 17 and earlier an anonymous class in an instance method still holds the outer reference even if it only uses the local. In that case pair this fix with a static nested class, asCloserdoes above. - Remove the registration. Pair every
addListenerwith aremoveListenerin a lifecycle method such asclose(). This fixes the leak without changing class structure, but it depends on every caller doing the cleanup. - Hold the outer object weakly. When a class must reach back to the outer instance but should not keep it alive, store a
WeakReferenceand check it before use:
import java.lang.ref.WeakReference;
public class Window {
private final String title;
public Window(String title) { this.title = title; }
static class TitleReader implements Runnable {
private final WeakReference<Window> ref;
TitleReader(Window w) { this.ref = new WeakReference<>(w); }
@Override
public void run() {
Window w = ref.get();
if (w == null) {
System.out.println("window already collected");
} else {
System.out.println("title = " + w.title);
}
}
}
public static void main(String[] args) {
Window w = new Window("main");
new TitleReader(w).run(); // title = main
}
}The static nested class reads w.title directly because nested classes may use each other's private members.
Lambdas and the same trap
A lambda captures this only if its body uses an instance member or this itself. () -> System.out.println(title) inside an instance method reads the field title, so it holds the enclosing instance. If the body only uses a local copy, String t = title; return () -> System.out.println(t);, the lambda holds just that string. A lambda that uses neither is typically a single shared object, which is why lambdas are usually lighter than anonymous classes.
This is the difference that matters for retention. An anonymous class in an instance context captures this whether or not you use it (before the JDK 18 optimization), while a lambda captures it only when it must.
Diagnosing a suspected leak
When memory grows and you suspect hidden references, work from the data:
- Take a heap dump (
jcmd <pid> GC.heap_dump file.hprof) and open it in a tool such as Eclipse MAT or VisualVM. - Find instances of the large class that should be gone, and ask for the path to the GC roots.
- Look for
this$0in the path. A step likeScreen$1.this$0names the anonymous class that is retaining the outer object, and the class name points you to the source line.
Exercise
A Controller class registers new Runnable() { public void run() { refresh(); } } in a static List<Runnable>, where refresh() is an instance method of Controller. Controllers are created and discarded often, and memory grows. Explain why, and give two ways to fix it.
Show answer
The anonymous class is created in an instance method, so it holds a hidden this$0 reference to its Controller. The static list is a GC root, so every registered Runnable keeps its Controller (and everything that Controller references) reachable even after the program drops it. Fix 1: remove the Runnable from the list when the Controller is closed, for example in a close() method. Fix 2: register a static nested class that holds a WeakReference<Controller> and calls refresh() only if get() returns a non-null value. Making the callback independent of the Controller instance, by passing in only the data it needs, also works.
Exercise
Why does an anonymous class created inside a static method not hold an outer reference, while one created in an instance method does?
Show answer
An inner or anonymous class needs an enclosing instance to resolve Outer.this and unqualified instance members. A static method has no this, so no enclosing instance exists, and the compiler adds no hidden field. In an instance method, this exists, so the compiler passes it to the anonymous class constructor and stores it in this$0. Since JDK 18, the field is omitted when the class never uses it, but the language does not guarantee that.