Java Thread Garbage collected or not Java Thread Garbage collected or not multithreading multithreading

Java Thread Garbage collected or not


A running thread is considered a so called garbage collection root and is one of those things keeping stuff from being garbage collected. When the garbage collector determines whether your object is 'reachable' or not, it is always doing so using the set of garbage collector roots as reference points.

Consider this, why is your main thread not being garbage collected, no one is referencing that one either.


As was explained, running threads are, by definition, immune to GC. The GC begins its work by scanning "roots", which are deemed always reachable; roots include global variables ("static fields" in Java-talk) and the stacks of all running threads (it can be imagined that the stack of a running thread references the corresponding Thread instance).

However, you can make a thread a "daemon" thread (see Thread.setDaemon(boolean)). A daemon thread is no more garbage-collected than a non-daemon thread, but the JVM exits when all running threads are daemon. One way to imagine it is that every thread, when it terminates, checks whether there remain some non-daemon running threads; if not, the terminating thread forces a System.exit() call, which exits the JVM (killing off the running daemon threads). This is not a GC-related issue; in a way, threads are allocated manually. However, this is how the JVM can tolerate semi-rogue threads. This is typically used for Timer instances.


The JVM has a reference to all running threads.

No thread (or the things it refers to) will be garbage-collected while it is still running.