Will Handler Inside A Method Leak Memory?
I know handler declared in a class may leak memory since it holds a reference to its outer class. In this case, we should use static nested class with weak reference. But What if
Solution 1:
It can under certain conditions. If the runnable passed is an anonymous or inner class, as in your example, it holds an implicit reference to 'this' and prevents 'this' from being garbage collected until the runnable is processed off the queue (so if your method never runs, like if your handler thread gets stopped without clearing the queue, it will leak).
In the case where you are worried about the conditions for a memory leak occurring or hanging onto objects too long, then you need to make your runnable a static class that has a weak reference initialized in the constructor, something like:
privatestatic MyRunnable implementsRunnable
{
privatefinal WeakReference<MyClass> myClass_weakRef;
publicMyRunnable(MyClass myClassInstance)
{
myClass_weakRef = newWeakReference(myClassInstance);
}
@Overridepublicvoidrun()
{
MyClassmyClass= myClass_weakRef.get();
if(myClass != null)
myClass.methodB();
}
}
privatevoidMethodA()
{
Handlerhandler=newHandler();
handler.postDelayed(newMyRunnable(this), 10*1000);
}
Post a Comment for "Will Handler Inside A Method Leak Memory?"