This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes Threads and Synchronization and the fly likes killing a Thread ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "killing a Thread ?" Watch "killing a Thread ?" New topic
Author

killing a Thread ?

kri shan
Ranch Hand

Joined: Apr 08, 2004
Posts: 1381
How to kill active thread using java.util.Concurrent package ?
Sebastian Janisch
Ranch Hand

Joined: Feb 23, 2009
Posts: 1183
If you are working with Thread on the low level than the usual implementation is to override interrupt in your Thread an set a boolean flag to true. Within the run method you implement various checks if that variable was set to true and hence quit the run method.


JDBCSupport - An easy to use, light-weight JDBC framework -
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 4181
    
  21

kri shan wrote:How to kill active thread using java.util.Concurrent package ?


Do you mean using the ExecutorServices? Can you describe exactly what you want to do?

If you wanted to kill a particular task submitted to an ExecutorService then you would use the Future generated by the executor. The task you put into an ExecutorService are Runnables. Make the Runnables respond to interruption by checking the Thread.currentThread.isInterrupted() or Thread.interrupted() methods (ie, if one returns true, the task stops working, cleans up, and returns). You would then take the Future object the ExecutorService generated and call tasksFuture.cancel(true) on it.

If you want to cancel all tasks / threads running on an executor then you should make sure your tasks respond to interruption as above, and then you can call ExecutorService#shutdown().

If you want to make sure that the ExecutorService kills its Threads when all tasks are complete, then call the ExecutorService#shutdown() method after submitting all your tasks, or provide a ThreadFactory to the executor that generates Daemon threads so they shutdown automatically when the application completes.
 
 
subject: killing a Thread ?