wood burning stoves
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
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "killing a Thread ?" Watch "killing a Thread ?" New topic

killing a Thread ?

kri shan
Ranch Hand

Joined: Apr 08, 2004
Posts: 1428
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

Joined: Jan 28, 2003
Posts: 4181

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.
I agree. Here's the link: http://aspose.com/file-tools
subject: killing a Thread ?
It's not a secret anymore!