Java Concurrency Interview

Threads and lifecycle question 11 of 180 senior

Can a thread be garbage collected while it is running?

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.

gc memory

Quiz yourself on Threads and lifecycle Suggest a correction