如何/当一个处理器垃圾回收? [英] How/when is a Handler garbage collected?

查看:98
本文介绍了如何/当一个处理器垃圾回收?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在类矿,我有以下code:

  mHandler = createHandler();

私人处理程序createHandler(){
    返回新的处理程序(){
        公共无效的handleMessage(信息MSG){
            更新();
            如果(!暂停){
                sendEmptyMessageDelayed(0,300);
            }
        }
    };
}
 

该文件说:

<一个href="http://developer.android.com/reference/android/os/Handler.html">http://developer.android.com/reference/android/os/Handler.html

  

每个处理程序实例与单个线程关联,而线程的消息队列

所以,如果我理解正确的处理程序是不是垃圾收集,只要应用程序线程运行,是正确的?

在我具体的例子,因为该处理器是它有一个隐含的引用封闭对象和指向由其对象的整个层次的匿名内部类。这在我看来就像一个配方内存泄漏。

顺便说一句,我可以使处理器停止发送的消息(这就是为什么我有如果(!暂停)),但是这不会使其成为GCed,对不对?

那么,有没有办法消除从消息队列的处理程序,并让它成为GCed?

解决方案
  

在我具体的例子,因为该处理器是它有一个隐含的引用封闭对象和指向由其对象的整个层次的匿名内部类。

您可以使用静电减少到几乎没有的潜在泄漏的影响嵌套类,而不是匿名内部类。

Inside a class of mine I have the following code:

mHandler = createHandler();

private Handler createHandler() {
    return new Handler() {
        public void handleMessage (Message msg) {
            update();
            if (!paused) {
                sendEmptyMessageDelayed(0, 300);
            }
        }
    };
}

The documentation says:

http://developer.android.com/reference/android/os/Handler.html

Each Handler instance is associated with a single thread and that thread's message queue

So if I understood correctly the Handler is not garbage collected as long as the application thread is running, is that correct?

In my specific example since the Handler is an anonymous inner class it has an implicit reference to the enclosing Object and the whole hierarchy of objects that is pointed by it. This looks to me like a recipe for memory leaking.

Btw, I can make the Handler stop sending messages(that's why I have the if (!paused)) but this won't make it be GCed, right?

So is there a way to remove the Handler from the message queue and get it to be GCed?

解决方案

In my specific example since the Handler is an anonymous inner class it has an implicit reference to the enclosing Object and the whole hierarchy of objects that is pointed by it.

You could reduce the impact of the potential leak to almost nothing by using a static nested class instead of an anonymous inner class.

这篇关于如何/当一个处理器垃圾回收?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆