Skip to main content

detect idle thread

2 replies [Last post]
Joined: 2006-01-17

what is the java proof way of detecting an idle java thread?

basically I want to terminate it if not currently actively executing code, from outside the thread.

Thanks in advance for your help.

-Jer A.

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
Joined: 2005-07-11

It probably depends a bit on how your threads operate. For threads that pull tasks off a work queue, just queue up a task telling the thread to exit from the run() method. Don't forget to null out any references to the Thread object once it has exited run(), though.

How to detect an idle thread is a different story. I suppose the thread could keep some thread local time stamps of when it last accepted a task or total elapsed time counter for executing tasks and those pieces of instrumentation could be used to decided if the thread should exit. You might also try using

Ultimately, though, unless you have large numbers of threads an idle thread probably isn't costing you much. There's a thread stack and the Java heap space consumed by any objects that the thread maintains references to. You have to weigh that against the cost of starting up new threads in the future. Thread creation times aren't too bad on more recent OSs, but they certainly are more costly to create than plain old objects.

Joined: 2005-05-23

Perhaps I'm reading into the question, but the phrase "from another thread" makes me think the question is really: "How do I know if a thread is idle so that I can call Thread.stop() safely."

The answer to that question is never; it is never safe to call Thread.stop(). Even if you "know" that the target thread is idle, it could wake up at the same time the stop method is called, acquire some state in the VM, and cause errors when it is stopped.

One addition to Brian's suggestions: if you know that the thread is idle and want it to exit, set some flag somewhere and interrupt tht thread. In the InterruptedException handler of the target thread, you can examine the flag (or possibly, just exit -- you don't necessarily need a flag since the fact that you were interrupted means that the thread should exit, but that will depend on your program).