简体   繁体   English

当一个对象持有对正在运行的线程的引用时,它是否有资格进行垃圾回收?

[英]Can an object be eligible for garbage collection when it holds a reference to a running Thread?

1) Actually the question is in the code. 1)实际上问题出在代码中。 Will holding a reference to a running Thread prevent an object from being eligible for garbage collection? 持有对正在运行的线程的引用会阻止对象符合垃圾回收的条件吗?

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) And would it be eligible if we used WeakReference to Thread instead of Thread? 2)如果我们使用WeakReference而不是Thread,它是否符合条件?

Updated 更新

Updated the code to emphasize the question that is bothered me the most. 更新了代码以强调最困扰我的问题。

What I'm trying to understand, whether the instance running thread blocks the object from being collected? 我想要了解的是,运行线程的实例是否阻止对象被收集?

Being eligible for garbage collection is a matter of who holds a reference to you , not of to whom you hold a reference. 有资格进行垃圾收集是由谁来提及你的 ,而不是你持有参考资料的人。 Thus yes, an object that has an instance variable containing a reference to a running Thread can be eligible for garbage collection if it is not itself reachable from any live thread. 因此,具有包含对正在运行的Thread的引用的实例变量的对象可以有资格进行垃圾收集,如果它本身不能从任何活动线程访问。 That is in fact the case in your example, at the line you marked. 事实上,在您的示例中,就是您标记的行。

If such an object is collected, that will have no effect on the Thread in question. 如果这样的目标收集,将有问题的线程没有影响。 In particular, the VM itself holds a reference to each living Thread (even if it is not currently running), so no other reference to a Thread is needed to keep it from being collected. 特别是,VM本身拥有对每个活动Thread的引用(即使它当前没有运行),因此不需要其他对Thread引用来防止它被收集。

Of course, holding a weak reference to a thread also does not prevent an object from being garbage collected. 当然,保持对线程的弱引用也不会阻止对象被垃圾回收。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM