views:

171

answers:

4

How can I find out who created a Thread in Java?

Imagine the following: You use ~30 third party JARs in a complex plugin environment. You start it up, run lots of code, do some calculations and finally call shutdown().

This life-cycle usually works fine, except that on every run some (non-daemonic) threads remain dangling. This would be no problem if every shutdown was the last shutdown, I could simply run System.exit() in that case. However, this cycle may run several times and it's producing more garbage every pass.

So, what should I do? I see the threads in Eclipse's Debug View. I see their stack traces, but they don't contain any hint about their origin. No creator's stack trace, no distinguishable class name, nothing.

Does anyone have an idea how to address this problem?

+4  A: 

I religiously name my threads (using Thread(Runnable, String), say), otherwise they end up with a generic and somewhat useless name. Dumping the threads will highlight what's running and (thus) what's created them. This doesn't solve 3rd party thread creation, I appreciate.

Brian Agnew
A: 

Unfortunately it doesn't. Within Eclipse I see all the blocking threads, but their stack traces only reflect their internal state and (apparently) disclose no information about the location of their creation. Also from a look inside the object (using the Variables view) I was unable to elicit any further hints.

EoH
"unfortunately it doesn't" -- what's "it" and what doesn't it do?
Jason S
"solve 3rd party thread creation"
EoH
A: 

When debuging your Eclipse application, you can stop all thread by clicking org.eclipse.equinox.launcher.Main field in the debug view.

Then from there, for each thread you can see the stack trace and goes up to the thred run method.

Sometimes this can help and sometimes not.

As Brian said, it a good practice to name threads because it's the only way to easily identify "who created them"

Manuel Selva
As I already stated I did this and it's of no help in this case. And I repeat: I *did not* create these threads.
EoH
As I said, I think the name is the only quick solution for that. Since the "creator" of these thread didn't named it I think the solution you mentioned (debuging Thread.start()) is the only one ....
Manuel Selva
A: 

Okay, I was able to solve (sort of) the problem on my own: I put a breakpoint into

Thread.start()

and manually stepped through each invocation. This way I found out pretty quickly that Class.forName() initialized lot of static code which in return created these mysterious threads.

While I was able to solve my problem I still think the more general task still remains unaddressed.

EoH