Sub topic 12
Hidden Outer References and Memory Retention
This chapter assumes you can create Java classes, understand instance and static members, and use interfaces and anonymous classes. You should also know that the garbage collector removes objects that are no longer reachable from live program roots such as running threads and static fields.
How an inner class retains its outer object
A non-static member class is tied to one instance of its enclosing class. Java stores that relationship internally. The inner object can use the outer object through Outer.this, so the outer object must remain reachable while the inner object needs it.
public class RetentionDemo {
static class Owner {
private final byte[] largeData = new byte[10_000_000];
class Job {
int dataSize() {
return Owner.this.largeData.length;
}
}
static class StaticJob {
int dataSize() {
return 0;
}
}
}
public static void main(String[] args) {
Owner owner = new Owner();
Owner.Job job = owner.new Job();
owner = null;
// The Owner object is still reachable through job.
System.out.println(job.dataSize());
Owner.StaticJob staticJob = new Owner.StaticJob();
// staticJob has no enclosing Owner instance.
System.out.println(staticJob.dataSize());
}
}The assignment owner = null removes one reference, but it does not make the Owner object eligible for garbage collection. The job object still refers to its enclosing Owner. Therefore, largeData also remains reachable through that Owner.
A static nested class does not have an automatic reference to an enclosing instance. It can still retain an outer object if you explicitly store one in a field, but Java does not create that relationship automatically.
When retention becomes a problem
Retention matters when the inner object lives longer than the outer object was expected to live. Common examples include:
- A listener stored by a long-lived service.
- A callback submitted to an executor.
- A task placed in a queue.
- An inner object stored in a cache.
- A timer or thread that keeps a callback alive.
The outer object is not leaked in the strict sense if the inner object still needs it. The problem is accidental retention: the program keeps a large object alive only because a small helper object remains registered somewhere.
For example, an instance method might register an anonymous callback:
service.register(new Runnable() {
@Override
public void run() {
System.out.println(largeField);
}
});This callback uses an instance field, so it needs the enclosing this. If service remains alive, the callback can keep the original object alive as well.
Lambdas and captured `this`
Lambdas follow the same reachability rule when they capture values. A lambda that reads an instance field captures the enclosing this:
class Session {
private final String user;
Runnable callback() {
return () -> System.out.println(user);
}
}The returned lambda can keep the Session object reachable. A lambda that uses only method parameters or local variables does not need to capture the enclosing instance.
Local and anonymous classes can also capture local variables. Captured local variables must be final or effectively final. Capturing a value copies or stores the value; capturing this keeps the enclosing object reachable.
How to avoid accidental retention
Use a static nested class when the helper does not need an outer instance. Pass only the data the helper actually needs. Unregister listeners when their owner is closed. Avoid placing callbacks in global collections unless their lifetime is intentional.
A WeakReference can be useful for specialized cache or listener designs, but it changes program behavior because the referenced object may disappear at any time. Prefer explicit ownership and cleanup first.
Exercise
A long-lived executor stores a Runnable created inside an instance method. The Runnable reads an instance field. What object may remain reachable, and why?
Show answer
The Runnable may capture the enclosing this reference. The executor can therefore keep the original outer object, and everything reachable from it, alive until the Runnable is removed or discarded.