1)实际上问题出在代码中。持有对正在运行的Thread的引用是否会阻止对象符合垃圾回收的条件?
class SomeClass {
Thread mThread = new Thread(new MyRunnable());
public SomeClass() {
mThread.start();
}
public static void main(String[] args) {
SomeClass sc = new SomeClass();
sc = null;
// Will the sc be eligible to gc here?
...
}
private static class MyRunnable implements Runnable {
@Override
public void run() {
while (true) {}
}
}
}
2)如果我们将WeakReference用于Thread而不是Thread,它是否符合条件?
更新
更新了代码,以强调最困扰我的问题。
我试图理解的是,运行线程的实例是否会阻止对象被收集?
答案 0 :(得分:10)
有资格进行垃圾收集的问题在于谁拥有对你的引用,而不是你持有引用的人。因此,具有包含对正在运行的Thread
的引用的实例变量的对象可以有资格进行垃圾收集,如果它本身不能从任何活动线程访问。实际上,在您的示例中,就是您标记的行。
如果收集了这样的对象,那么对相关的线程没有任何影响。特别是,VM本身拥有对每个生命Thread
的引用(即使它当前没有运行),因此不需要对Thread
进行其他引用以防止它被收集。
当然,保持对线程的弱引用也不会阻止对象被垃圾回收。