Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

killing a Thread ?

 
kri shan
Ranch Hand
Posts: 1473
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How to kill active thread using java.util.Concurrent package ?
 
Sebastian Janisch
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic