Search code examples
javaandroidandroid-activitymemory-leaksgarbage-collection

Why in GC the references from Views are cleaned, while the references from nested inner class remain when the containning Activity is destroyed?


I have read lots of articles about memory leak. All of them tell me that if an Activity contains a (non-static) nested inner class or (non-static) anonymous inner class, then the Activity may not be cleaned by garbage collection when it is destroyed, since the (non-static) nested inner class contains a reference to its outer class (i.e., the Activity). They also suggest that I should use static inner class as possible (so I have to change all the nested inner classes to static classes, really bad practices)

But I can't understand, why the references of View objects won't prevent their containing Activity from being cleaned? The references from views, and the reference from nested inner classes, in my opinion, are not so much different inside a same Activity.


Solution

  • The problem is not having a non-static inner class or anonymous class. This is not a problem. The GC handles circular references just fine and it will detect that the inner/anonymous class references the Activity and it will clean up everything. No problem.

    The problem occurs is when you store a reference to a non-static inner/anonymous class in a static variable OR if you pass a reference to another component that holds onto that reference. In these cases, the Activity cannot be garbage-collected because there is still a live object or static variable that contains a reference to the inner/anonymous class.

    Unfortunately, a lot of the articles warning about memory leaks are incorrect, incomplete, or not detailed enough to describe the problem exactly.