在匿名类中使用最终变量时的垃圾收集 [英] Garbage collection when final variables used in anonymous classes

查看:114
本文介绍了在匿名类中使用最终变量时的垃圾收集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我的代码类似于以下代码:

  public Constructor(final Object o){
taskSystem。添加(新的CycleTask(15,15,-1){

@Override
public void execute()throws Throwable {
//在这里每15个周期永远存取
}
});
}

何时会收集垃圾?只有当任务已经收集完毕,或者它会永久保留在内存中,因为它是最终的? o 可能一旦无法再获取垃圾回收,无论是否为最终垃圾回收。显然,只要 execute 正在运行,如果它需要访问 o ,它将阻止GC。



execute 完成运行时,假设您没有存储对 o (例如在一个集合中),它将被标记为可以进行垃圾回收。


If I have code similar to the following:

public Constructor(final Object o) {
    taskSystem.add(new CycleTask(15, 15, -1) {

        @Override
        public void execute() throws Throwable {
            //access o here every 15 cycles forever
        }
    });
}

When would o be garbage collected, if ever? Only when the task has been collected, or will it remain in memory forever because it's final?

解决方案

o might get garbage collected once it is not reachable any longer, whether it is final or not. Obviously, as long as execute is running, if it needs to access o, it will prevent GC.

When execute is done running, and assuming you have not stored any references to o (for example in a collection), it will be flagged as ready for garbage collection.

这篇关于在匿名类中使用最终变量时的垃圾收集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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