Will handler inside a method leak memory?

2019-07-05 05:06发布

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");
}

2条回答
闹够了就滚
2楼-- · 2019-07-05 05:19

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);
}
查看更多
三岁会撩人
3楼-- · 2019-07-05 05:41

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.

查看更多
登录 后发表回答