I'm starting my thread like so:
(new MyThread()).start();
I'm not keeping a reference to it anywhere, so I'm wondering if it's a safe approach - can't GC collect it since it's not referenced?
If not (I think so), then why?
I'm starting my thread like so:
(new MyThread()).start();
I'm not keeping a reference to it anywhere, so I'm wondering if it's a safe approach - can't GC collect it since it's not referenced?
If not (I think so), then why?
If you look at the OpenJDK Java 7 source code of Thread
, you'll notice that start()
contains the following
group.add(this);
where group
is the Thread
's ThreadGroup
which is managed by the JVM. So there is always a reachable reference to the Thread
while it is still running. It won't be garbage collected
If this alone isn't convincing, consider that starting a new thread means creating a new call stack where the root call is one of Thread
's methods, probably some native
method. You can't be executing the method of an object if the object is garbage collected. As such, the Thread
object must still be alive.