Does the GC clear memory of running threads with no reference to them ?
Consider the following code:

Thread t = new Thread()...
t = null;

Suppose 't' runs forever, and the rest of the program runs forever - will the GC clean 't' from the memory (stop it in the middle of the running) ? It's running but it has no reference to it.

Please if you have link to an official page from SUN/Oracle that support the answer, write it here, because I searched and did not find an official answer to it.


Recommended Answers

All 7 Replies

A thread will continue executing until its run() method terminates, at which point it dies and cannot be restarted. I think the GC issue is a red herring - although you may have freed all your explicit references to it, the JVM scheduler surely has one.
This http://www.janeg.ca/scjp/threads/state.html useful summary isn't from Sun/Oracle, but it does reference them.

I can see your point that the thread remains alive, it make sense, but I did not find it written in SUN / Oracle official pages...

You'll find some strong clues in the JavaDoc for Thread and ThreadState, but I can't find anything from Sun/Oracle that documents this properly. It must be somewhere?

I don't know.
well it makes sense that the thread will not die in the middle as said above, I just wanted to be sure by an official documentation.
Thanks for the responses.

This is because each thread spawned is effectively a garbage collection root i.e. the central point at which the GC starts working. As far as an official source is concerned, the same is mentioned (but in a bit cryptic way) here (read the unreachable section).

Thanks !

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.