views:

203

answers:

4

I have an application which has to live as a service, I create an object which then spawns off a buch of threads.

If I set the only reference to that object to null will all the child threads get cleaned up? or will I suffer from a memory leak.

Do I have to explicitly terminate all the child threads?

A: 

No matter the theory (or StackOverflow answers), you should also create some test to see if what you intended to do, is really happening. Maybe you have some forgotten pointer preventing garbage collection.

GvS
+5  A: 

Yes, you need to make sure your other threads stop. The garbage collector is irrelevant to this. You should also do so in an orderly fashion though - don't just abort them.

Here's a pattern in C# for terminating threads co-operatively - it's easy to translate to Java.

Jon Skeet
+7  A: 

Threads and static references are 'root objects'. They are immune from GCing and anything that can be traced back to them directly or indirectly cannot be collected. Threads will therefore not be collected as long as they are running. Once the run method exits though, the GC can eat up any unreferenced thread objects.

izb
I like your explanation because it says "Why", but you might want to fix one small point. It's not things that Touch threads, but things that threads touch. A reference to a thread will not stop an object from being gc'd, only a reference from a thread..
Bill K
You're right of course.
izb
+2  A: 

As others have mentioned, threads won't be cleaned up until they've been stopped. They are root objects for the GC, so you don't have to keep references to them. Your application won't quit until all threads have exited.

There is one exception to this rule. If you mark a thread as a daemon then it will not prevent your application from exiting, and if there are no other non-daemon threads running they it will be cleaned up automatically.

See the javadoc for Thread for more info.

Herms