Java › Inner Classes & Anonymous Classes
How does an inner class's implicit reference to its outer instance create a potential memory leak risk, and in what specific scenario does this become a genuine practical concern?
IntermediateAnswer
Since a non-static inner class instance holds an implicit strong reference to its enclosing outer instance (via the synthetic this$0 field), keeping an inner class instance reachable (even indirectly, through some entirely unrelated long-lived reference chain) inadvertently also keeps its ENTIRE associated outer instance reachable and therefore un-garbage-collectible, even if nothing else in the application still needs that outer instance -- this becomes a genuine practical concern in scenarios like a long-lived event listener registry holding onto anonymous/inner class listener instances that were created from short-lived outer instances (like an Android Activity, a classic real-world example of this exact leak pattern), where the listener registry inadvertently prevents the entire outer instance (and everything IT references) from ever being collected, for as long as the registry itself lives.
public class Activity {
private byte[] largeData = new byte[100_000_000]; // 100MB, associated with this specific Activity instance
class Listener {
void onEvent() { /* handle event */ }
}
void registerWithLongLivedRegistry(EventRegistry registry) {
registry.add(new Listener()); // registry now indirectly keeps THIS ENTIRE Activity (and its 100MB) alive!
}
}Real-world example A mobile application experiences a well-known category of memory leak where short-lived Activity instances (each holding significant associated data) never get garbage collected because a long-lived, application-scoped event bus retained references to inner-class listener instances created by each Activity, each implicitly keeping its entire parent Activity (and all its data) alive far longer than intended, fixed by switching to static nested classes with explicit weak references to the outer instance where genuinely needed.