سؤال

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 a handler is declared inside a method. I faced below case and not sure is it a correct implementation. Could someone please explain or give me a hint? I even don't know what I should search for.

private void methodA(){
    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {            
        @Override
            public void run() {
            methodB();
        }
    }, 10*1000);

private void methodB(){
    //textView holds a reference to a activity
    textView.setText("hello");
}
هل كانت مفيدة؟

المحلول

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:

private static MyRunnable implements Runnable
{
    private final WeakReference<MyClass> myClass_weakRef;

    public MyRunnable(MyClass myClassInstance)
    {
        myClass_weakRef = new WeakReference(myClassInstance);
    }

    @Override
    public void run()
    {
        MyClass myClass = myClass_weakRef.get();
        if(myClass != null)
            myClass.methodB();
    }
}

private void MethodA()
{
    Handler handler = new Handler();
    handler.postDelayed(new MyRunnable(this), 10*1000);
}

نصائح أخرى

Creating a Handler inside your method isn't a special case. It falls under the same circumstances, in that the Message you post will live in the message queue until it's processed.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top