Will handler inside a method leak memory?

非 Y 不嫁゛ 提交于 2019-12-10 18:43:35

问题


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

回答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:

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



回答2:


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.



来源:https://stackoverflow.com/questions/22162642/will-handler-inside-a-method-leak-memory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!