Video in progress

Strong Middle 🧱 OOP and SOLID

How can a non-static inner class cause a memory leak?

An instance of a non-static inner class keeps a hidden reference (Outer.this) to the outer object. If the inner object ends up somewhere long-lived (a cache, a static list, another thread), it keeps the outer object and all its fields from being garbage collected.

📖 Answer

public class ReportPage {
    private final byte[] pdf = new byte[50 * 1024 * 1024];   // 50 MB

    class Row { String title; }          // non-static: holds ReportPage.this

    Row firstRow() { return new Row(); }
}

static final List<Object> CACHE = new ArrayList<>();
CACHE.add(new ReportPage().firstRow());   // a tiny Row is holding on to 50 MB

You see this in a heap dump (Eclipse MAT): Row → this$0 → ReportPage → byte[]. The retained size is much bigger than you expected.

The same thing happens with anonymous classes: a new Runnable() {...} created inside an instance method can also hold the outer object. Since JDK 18, javac may drop an unused outer reference, but don't write code that depends on that.

Rules:

  • if the inner class doesn't use the outer object's fields, make it static (the well-known advice from Effective Java);
  • nested declarations of records and enums are static automatically;
  • a lambda captures only what it actually uses: if it doesn't touch this, it doesn't keep the outer object.

Helper classes like builders, DTOs and iterators should almost always be a static class.