Inner classes that hold the outer object
35 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)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).
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
javac --release 17 ReportCard.javajavap -p 'ReportCard$Row' 'ReportCard$Header'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.Rowhas the fieldfinal ReportCard this$0, and its constructor takes aReportCard: everyRowis tied to one report card. Headerhas neither: it is created withnew ReportCard.Header()and knows nothing about any report card. The quotes stop the shell from treating$Rowas a variable; on Windows Command Prompt you can leave them out.
Example 2 · A small inner object keeps a 5 MB outer object alive
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()); }}Inner Mark kept -> paper collected? false Static Score kept -> paper collected? true Maths Q1: 8
What this code does
- Only a
Markis stored in the static table, butMarkis an inner class whoselabel()readssubject, so it holdsExamPaper.this. The paper and its 5 MB of scans can never be collected. Scoreis 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.
--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
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(); } }}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
Runnablemade inscheduleReport()reads the fieldbranch, so it holds the dashboard. Stored in the scheduler, it keeps Branch A's dashboard and its 5 MB of images alive. reportForis static, so its anonymous class has no outer object; it getsbranchas 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
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); }}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
studentNamecapturesthis, and so doesthis::greet: in both cases the stored reminder keeps the wholeFeeScreenwith its 5 MB of images. Thereminderslist is static, so it lives for the whole app. - The lambda that reads the local copy
namecaptures 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
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(); } }}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
FareWatcheris static and receivestrainNoandtravelClassin 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
FareWatcherbeen an inner class readingBookingPage.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