Reputation: 1154
I have a class structure that looks like this.
class A
{
B b;
A()
{
b = new B();
b.a = this;
}
}
class B
{
A a;
}
class C
{
A a = new A();
//a is ready for Garbage collection
a = null;
}
On activity Destroy(), I will set the variable a = null. But on heap, still I could see that variable b holds the reference for B.
Can anyone please explain this?
Upvotes: 0
Views: 263
Reputation: 912
In Java, non-static inner and anonymous classes hold an implicit reference to their outer class. Static inner classes, on the other hand, do not.
So if for example you are doing a long running operation on classes B or C, that will prevent the activity context from being garbage collected and leaking all of the application’s resources.
Another potential reason can be that you are not handling correctly background threads and these are still executed or have been scheduled for future execution. As Alex Lockwood has written on this post:
Don’t assume that Java will ever clean up your running threads for you.
Finally, you can integrate leakcanary which is a great tool for memory leak detection. It'll show you with a graph what object holds a reference and prevents garbage collection.
Upvotes: 1