在匿名类中使用最终变量时的垃圾收集 [英] Garbage collection when final variables used in anonymous classes
问题描述
如果我的代码类似于以下代码:
public Constructor(final Object o){
taskSystem。添加(新的CycleTask(15,15,-1){
@Override
public void execute()throws Throwable {
//在这里每15个周期永远存取
}
});
}
何时会收集垃圾?只有当任务已经收集完毕,或者它会永久保留在内存中,因为它是最终的? 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屋!