AfterWorkGuinness
AfterWorkGuinness

Reputation: 1850

Java Threads and Garbage Collection

I have read in countless places that running threads are garbage collection roots (ie they reside on the stack, the GC identifies them and traces through them to determine if the objects inside them are still reachable). Further more, a GC root will never be garbage collected itself.

My confusion is here: If the objects allocated from within a thread can never be garbage collected until the thread is stopped, how then is anything garbage collected in single-threaded programs where the only thread is the main thread ?

Clearly I'm missing something here.

Upvotes: 1

Views: 333

Answers (2)

Andy Thomas
Andy Thomas

Reputation: 86381

Objects are in the heap, regardless which thread created them.

Objects may be reachable through references. Some of these references can be on the call stack of one or more threads.

An object can be collected when there are no more references to it, regardless whether is allocating thread is still running or not.

For example, the thread below repeatedly allocates new StringBuilder objects. During a call to foo(), the thread has references on its call stack to a StringBuilder object. When foo() returns, there are no further references to the StringBuilder object. Therefore, that object is no longer reachable, and is eligible for garbage collection.

Thread thread = new Thread( new Runnable() {
    @Override
    public void run() {
        while ( true ) {
            foo();
        }
    }

    public void foo() {
        StringBuilder strBuilder = new StringBuilder("This new object is allocated on the heap.");
        System.out.println( strBuilder );
    }
});

thread.run();

Upvotes: 1

Stephen C
Stephen C

Reputation: 718738

First, a thread (stack) is only a GC root while it is alive. When the thread terminates, it is no longer a GC root.

My confusion is here: If the objects allocated from within a thread can never be garbage collected until the thread is stopped, how then is anything garbage collected in single-threaded programs where the only thread is the main thread ?

Your premise is incorrect.

It doesn't matter which thread allocates an object. What matters is whether an objects allocated by your thread remains reachable. If it become unreachable (for example, if you didn't put the object's reference into a local variable) ... then it can be collected.

Upvotes: 1

Related Questions