3

I am reading Efficient Android Threading, which says

Instead of using nested classes with outer class references, it is preferred to use static inner classes because they reference only the global class object and not the instance object. This just mitigates the leak, because all explicit references to other instance objects from the static inner class are still live while the thread executes.

But I am not clear why it mitigates the leak. If all explicit references to other instance objects from the static inner class are alive, isn't it a cause of memory leak contrary to the above explanation ?

myoldgrandpa
  • 871
  • 7
  • 21

1 Answers1

7

The non-static inner class will leak memory because it has an implicit reference to its outer class. Suppose you have an instance holds the reference to an inner class object which means it is active, and this inner class object holds an implicit reference to its outer class object which also means the outer class object is active, but it may not be used in fact. So for the outer class object, due to the reference from the inner class, it will not be removed by the garbage collection, resulting in leaking memory.

you can find more detail from this answer: When exactly is it leak safe to use (anonymous) inner classes?

heyang
  • 86
  • 1
  • I already understood what you are saying. The unclear part is the sentence "because all explicit references to other instance objects from the static inner class are still live while the thread executes." What does this sentence mean ? – myoldgrandpa Mar 22 '18 at 14:12