Want to have threads 'auto-destruct' or killed after a certain time period.

Right now I have some code that creates and starts threads to perform certain tasks. Some of the threads I care about so I wait for them to finish (join() with a reasonable timeout value). The problem is that there are some threads that I don't care whether they execute successfully or not so I don't want to wait for them but I would like to be able to kill or interrupt them if they hang. Is there a way to have a thread stopped after a certain amount of time without having to wait on it? Am I stuck with either waiting or creating another thread just to watch these guys?

[585 byte] By [MePacoa] at [2007-11-27 9:03:14]
# 1
Even having a "watcher thread" won't help, because there's no safe way to stop a thread without the co-operation of the thread itself.Better is to write your code so it doesn't hang! :-)
dannyyatesa at 2007-7-12 21:35:02 > top of Java-index,Core,Core APIs...
# 2

If it were me, I would look for ways to stop the threads cleanly - either set a boolean flag via API or let them die naturally. If they hang, it might be a symptom of another problem.

If that won't do it, and there's a good reason why they hang, you might consider using a ThreadPoolExecutor, and have it execute the threads you aren't particularly concerned about. When you need to kill them, you can use its shutdownNow (boolean mayInterruptIfRunning) method.

BinaryDigita at 2007-7-12 21:35:02 > top of Java-index,Core,Core APIs...
# 3

Thanks for the quick replies. Unfortunately, the code I'm executing in the other thread won't always be something I've written because we have the facilities to allow users (other developer groups) to plug in their own code. I'll look at the ThreadPoolExecutor but I guess in the end it isn't my problem. If their code is so bad that it hangs then they deserve to have a bunch of stalled threads sitting around.

MePacoa at 2007-7-12 21:35:02 > top of Java-index,Core,Core APIs...