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.
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 http://java.sun.com/j2se/1.5.0/docs/api/java/lang/management/ThreadMXBea....
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.
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).
Your use of this web site or any of its content or software indicates your agreement to be bound by these Terms of Participation.
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective owners.