Thread garbage collection  
Author Message
Maggie





PostPosted: 2004-11-18 12:21:00 Top

java-programmer, Thread garbage collection What happens if a Thread is available for garbage collection yet still
running?

I guess the answer is obvious. The thread executes to completion or is
terminated with the garbage collection process at some later unguaranteed
time. Correct?

I'm asking because I'm reusing the same reference to a thread to create a
new one on an event. I just realized that I'm probably leaving a ton of
orphaned threads (which will soon be fixed).

Thanks!


 
Chris Smith





PostPosted: 2004-11-18 12:36:00 Top

java-programmer >> Thread garbage collection Maggie <email***@***.com> wrote:
> What happens if a Thread is available for garbage collection yet still
> running?

That's not possible. When a thread is running, it can obtain an
instance of its java.lang.Thread object, so a java.lang.Thread object is
never eligible for garbage collection while the thread is still running.

> I guess the answer is obvious. The thread executes to completion or is
> terminated with the garbage collection process at some later unguaranteed
> time. Correct?

No. The garbage collector only reclaims unused objects. It does not
terminate threads, ever.

> I'm asking because I'm reusing the same reference to a thread to create a
> new one on an event. I just realized that I'm probably leaving a ton of
> orphaned threads (which will soon be fixed).

If these threads continue to run forever, you're in a pretty bad
situation with that code. Better fix it as soon as you possibly can,
and if it's deployed, try to minimize its usage until you can fix the
problem.

If your threads don't continue to run forever, then your situation is
still not very good, but not as critical as in the first case. Best to
fix this by using a thread pool instead of spawning a new thread every
time a new background task (such as event notification) needs to be
done. Java 1.5 even has standard implementations of thread pools pre-
made for you to use; see the java.util.concurrent package, and
specifically the Executor interface and its related classes and
interfaces.

--
www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation