如何/当一个处理器垃圾回收?处理器、垃圾

2023-09-06 00:12:32 作者:花孞花汐亦花心

在类矿,我有以下code:

  mHandler = createHandler();

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

该文件说:

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.