savak
savak

Reputation: 211

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. 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?

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?

Upvotes: 2

Views: 133

Answers (1)

John Bollinger
John Bollinger

Reputation: 180538

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. 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.

Of course, holding a weak reference to a thread also does not prevent an object from being garbage collected.

Upvotes: 10

Related Questions