Threads and lifecycle question 11 of 180 senior
Can a thread be garbage collected while it is running?
- Yes, if you drop the last reference to the
Threadobject - Correct: No, a started and not yet terminated thread is a GC root, so it and everything it references stay alive
- Only daemon threads are collectable
- Only if it is parked
Live threads are GC roots. A running thread keeps its stack, every object reachable from it and its
ThreadLocal map alive, whether or not anyone still holds a reference to the Thread object.
That is the mechanism behind two classic leaks. A thread you started and forgot ("thread leakage")
holds its whole object graph forever. And a ThreadLocal on a pooled thread is never collected
between tasks, because the thread outlives them all, which is why a ThreadLocal that is not removed
in a finally block leaks in a web container.