Skip to lesson

Inner classes that hold the outer object

An inner class object always knows which outer object created it, so it can read the outer object's fields. That knowledge is a hidden reference, and if the small inner object lives long, it keeps the whole outer object alive with it.

A non-static inner class keeps a hidden reference to Outer.this

An inner class is a non-static class declared inside another class. Each inner object keeps a hidden reference to the outer object that created it, so keeping one alive keeps the other alive.

An inner class is a class declared inside another class without static. Each inner object belongs to one outer object, and to make that work javac adds a hidden field, usually named this$0, that points to the outer object (Outer.this).

ReportCard.javaJava
public class ReportCard {    private final String student = "Asha";    private final int[] marks = {91, 78, 85};
    class Row {                          // inner class: uses the outer object's fields        String line(int i) {            return student + ": " + marks[i];        }    }
    static class Header {                // static nested class: no outer object        String text() { return "Name : Marks"; }    }}

A static nested class has no such field: it is just a class that lives inside another class's name.

This matters when the inner object outlives the outer one. Put a small inner object into a static list, a cache or a listener registry, and the outer object, with all its fields, stays reachable for as long as the inner object does. A 40-byte object can keep a 5 MB one alive. Rule of thumb: make a nested class static unless it really needs the outer object.

Example 1 · javap shows the hidden field

Terminal
javac --release 17 ReportCard.javajavap -p 'ReportCard$Row' 'ReportCard$Header'
Output
Compiled from "ReportCard.java"
class ReportCard$Row {
  final ReportCard this$0;
  ReportCard$Row(ReportCard);
  java.lang.String line(int);
}
Compiled from "ReportCard.java"
class ReportCard$Header {
  ReportCard$Header();
  java.lang.String text();
}

What this code does

  • A real run with JDK 21's javac and javap -p (show private members) on the snippet above. Row has the field final ReportCard this$0, and its constructor takes a ReportCard: every Row is tied to one report card.
  • Header has neither: it is created with new ReportCard.Header() and knows nothing about any report card. The quotes stop the shell from treating $Row as a variable; on Windows Command Prompt you can leave them out.

Example 2 · A small inner object keeps a 5 MB outer object alive

InnerLeakDemo.javaJava
import java.lang.ref.WeakReference;import java.util.ArrayList;import java.util.List;
class ExamPaper {    final byte[] scannedPages = new byte[5_000_000];    final String subject;
    ExamPaper(String subject) {        this.subject = subject;    }
    class Mark {                                        // inner: has a hidden ExamPaper.this        final int question;        final int marks;
        Mark(int question, int marks) {            this.question = question;            this.marks = marks;        }
        String label() {            return subject + " Q" + question + ": " + marks;        }    }
    Score score(int question, int marks) {        return new Score(question, marks);    }
    static class Score {                                // static nested: no outer reference        final int question;        final int marks;
        Score(int question, int marks) {            this.question = question;            this.marks = marks;        }    }}
public class InnerLeakDemo {    static final List<Object> resultsTable = new ArrayList<>();   // lives for the whole run
    static boolean collected(WeakReference<?> ref) throws InterruptedException {        System.gc();        Thread.sleep(100);        return ref.get() == null;    }
    public static void main(String[] args) throws InterruptedException {        ExamPaper maths = new ExamPaper("Maths");        resultsTable.add(maths.new Mark(1, 8));        WeakReference<ExamPaper> mathsRef = new WeakReference<>(maths);        maths = null;        System.out.println("Inner Mark kept -> paper collected? " + collected(mathsRef));
        ExamPaper physics = new ExamPaper("Physics");        resultsTable.add(physics.score(1, 7));        WeakReference<ExamPaper> physicsRef = new WeakReference<>(physics);        physics = null;        System.out.println("Static Score kept -> paper collected? " + collected(physicsRef));        System.out.println(((ExamPaper.Mark) resultsTable.get(0)).label());    }}
Sample output
Inner Mark kept -> paper collected? false
Static Score kept -> paper collected? true
Maths Q1: 8

What this code does

  • Only a Mark is stored in the static table, but Mark is an inner class whose label() reads subject, so it holds ExamPaper.this. The paper and its 5 MB of scans can never be collected.
  • Score is a static nested class, so storing it keeps nothing else alive and the Physics paper is collected. The GC check makes this a sample output; on HotSpot with default settings it prints these lines.
javac 18 and later, compiling for Java 18 or newer (--release 18 or higher), leaves this$0 out when an inner or anonymous class never uses its outer object. With --release 17 it is always there. An inner class that does use the outer object, like Row, always has it, on every version.

Anonymous classes do the same

An anonymous class (new Runnable() { ... }) created inside an instance method is an inner class too. It gets the same hidden reference to the object whose method created it.

Example 3 · Anonymous class: instance method versus static method

AnonymousLeakDemo.javaJava
import java.lang.ref.WeakReference;import java.util.ArrayList;import java.util.List;
class Scheduler {    static final List<Runnable> jobs = new ArrayList<>();   // lives for the whole app}
class StoreDashboard {    final byte[] images = new byte[5_000_000];    final String branch;
    StoreDashboard(String branch) {        this.branch = branch;    }
    // Anonymous class in an instance method: it reads 'branch', so it holds StoreDashboard.this.    void scheduleReport() {        Scheduler.jobs.add(new Runnable() {            @Override            public void run() {                System.out.println(branch + ": daily report ready");            }        });    }
    // Anonymous class in a static method: there is no outer object to hold.    static Runnable reportFor(String branch) {        return new Runnable() {            @Override            public void run() {                System.out.println(branch + ": daily report ready");            }        };    }}
public class AnonymousLeakDemo {    static boolean collected(WeakReference<?> ref) throws InterruptedException {        System.gc();        Thread.sleep(100);        return ref.get() == null;    }
    public static void main(String[] args) throws InterruptedException {        StoreDashboard a = new StoreDashboard("Branch A");        a.scheduleReport();        WeakReference<StoreDashboard> refA = new WeakReference<>(a);        a = null;        System.out.println("Instance-method anonymous class -> dashboard collected? " + collected(refA));
        StoreDashboard b = new StoreDashboard("Branch B");        Scheduler.jobs.add(StoreDashboard.reportFor(b.branch));        WeakReference<StoreDashboard> refB = new WeakReference<>(b);        b = null;        System.out.println("Static-method anonymous class   -> dashboard collected? " + collected(refB));
        for (Runnable job : Scheduler.jobs) {            job.run();        }    }}
Sample output
Instance-method anonymous class -> dashboard collected? false
Static-method anonymous class   -> dashboard collected? true
Branch A: daily report ready
Branch B: daily report ready

What this code does

  • The anonymous Runnable made in scheduleReport() reads the field branch, so it holds the dashboard. Stored in the scheduler, it keeps Branch A's dashboard and its 5 MB of images alive.
  • reportFor is static, so its anonymous class has no outer object; it gets branch as a parameter. Branch B's dashboard is collected, and both jobs still print the right report.

Anonymous classes are often handed to long-lived owners, a scheduler, an event bus, a static comparator field, so they leak more often than named inner classes. An anonymous class created inside a static method has no outer object at all, because there is no this in a static method. Passing the values it needs as parameters to a static factory method is a simple way to avoid the hidden reference.

Lambdas capture this only when they use instance members

A lambda does not get a hidden outer reference automatically. It captures only what its body uses: local variables are copied in, and this is captured only if the body uses an instance field, an instance method or this itself.

Example 4 · What a lambda or method reference captures

LambdaCaptureDemo.javaJava
import java.lang.ref.WeakReference;import java.util.ArrayList;import java.util.List;import java.util.function.Function;import java.util.function.Supplier;
class FeeScreen {    final byte[] receiptImages = new byte[5_000_000];    final String studentName;
    FeeScreen(String studentName) {        this.studentName = studentName;    }
    String greet() {        return "Hello " + studentName;    }
    Supplier<String> usesField() {        return () -> "Reminder for " + studentName;      // reads this.studentName: captures this    }
    Supplier<String> usesLocalCopy() {        String name = studentName;        return () -> "Reminder for " + name;              // captures only the String    }
    Supplier<String> methodReference() {        return this::greet;                               // a bound method reference holds this    }}
public class LambdaCaptureDemo {    static final List<Supplier<String>> reminders = new ArrayList<>();
    static void check(String label, Function<FeeScreen, Supplier<String>> make)            throws InterruptedException {        FeeScreen screen = new FeeScreen("Asha");        Supplier<String> reminder = make.apply(screen);        reminders.add(reminder);        WeakReference<FeeScreen> ref = new WeakReference<>(screen);        screen = null;        System.gc();        Thread.sleep(100);        System.out.println(label + " -> screen collected? " + (ref.get() == null)                + "  (" + reminder.get() + ")");    }
    public static void main(String[] args) throws InterruptedException {        check("lambda reads a field ", FeeScreen::usesField);        check("lambda reads a local ", FeeScreen::usesLocalCopy);        check("this::greet          ", FeeScreen::methodReference);    }}
Sample output
lambda reads a field  -> screen collected? false  (Reminder for Asha)
lambda reads a local  -> screen collected? true  (Reminder for Asha)
this::greet           -> screen collected? false  (Hello Asha)

What this code does

  • The lambda that reads the field studentName captures this, and so does this::greet: in both cases the stored reminder keeps the whole FeeScreen with its 5 MB of images. The reminders list is static, so it lives for the whole app.
  • The lambda that reads the local copy name captures only the string, so the screen is collected. Each reminder still produces the same text.

So () -> "Hi " + name with name a field captures this; with name a local variable it captures only the string. A bound method reference such as this::refresh or screen::refresh also holds its receiver object. String::length or Screen::refresh (no object before ::) holds nothing. The habit that avoids the leak: before returning a lambda that will be stored somewhere long-lived, copy the field values it needs into local variables and use only those.

Fix: static nested classes

The standard fix is to make the class static and pass in exactly what it needs through its constructor. The compiler then enforces the rule: a static nested class cannot read the outer object's fields by accident, so the hidden reference cannot come back later.

Example 5 · The fix: a static nested watcher with copied values

StaticNestedFixDemo.javaJava
import java.lang.ref.WeakReference;import java.util.ArrayList;import java.util.List;
class PriceAlerts {    static final List<Runnable> watchers = new ArrayList<>();    // checked every minute, all day}
class BookingPage {    final byte[] seatMapImage = new byte[5_000_000];    final String trainNo;    final String travelClass;
    BookingPage(String trainNo, String travelClass) {        this.trainNo = trainNo;        this.travelClass = travelClass;    }
    // Before: an inner class that read trainNo and travelClass through BookingPage.this.    static class FareWatcher implements Runnable {        private final String trainNo;        private final String travelClass;
        FareWatcher(String trainNo, String travelClass) {            this.trainNo = trainNo;            this.travelClass = travelClass;        }
        @Override        public void run() {            System.out.println("Checking fare for " + trainNo + " " + travelClass);        }    }
    void watchFare() {        PriceAlerts.watchers.add(new FareWatcher(trainNo, travelClass));    }}
public class StaticNestedFixDemo {    public static void main(String[] args) throws InterruptedException {        List<WeakReference<BookingPage>> pages = new ArrayList<>();        String[][] searches = {{"12627", "3A"}, {"12951", "2A"}, {"22691", "SL"}};        for (String[] s : searches) {            BookingPage page = new BookingPage(s[0], s[1]);            page.watchFare();            pages.add(new WeakReference<>(page));        }                                      // the user closes each page
        System.gc();        Thread.sleep(100);        long alive = pages.stream().filter(r -> r.get() != null).count();        System.out.println("Watchers: " + PriceAlerts.watchers.size() + ", booking pages still in memory: " + alive);        for (Runnable w : PriceAlerts.watchers) {            w.run();        }    }}
Sample output
Watchers: 3, booking pages still in memory: 0
Checking fare for 12627 3A
Checking fare for 12951 2A
Checking fare for 22691 SL

What this code does

  • FareWatcher is static and receives trainNo and travelClass in its constructor. The long-lived alert list keeps three small watchers, and all three booking pages, each with a 5 MB seat map, are collected.
  • Had FareWatcher been an inner class reading BookingPage.this.trainNo, every page the user ever opened would stay in memory as long as its watcher did.

If the nested object really must reach the outer one, for example a background task that updates a screen, hold the outer object through a WeakReference and check get() for null, or remove the nested object (unregister, cancel) when the outer one closes. Named inner classes are still fine for short-lived helpers that never escape their outer object, such as an iterator used inside one loop. The leak appears only when the inner object lives longer than the outer object should.

Next step

Check your understanding

12 quick questions