How to interrupt a thread in java?


August 8, 2014 . Comments
Tags: java, Thread, JVM

 
 
  

Just like how the OS allows us to kill a long running task we should have the flexibility in our code to stop long running threads.

There are many ways to do this.

By calling the Thread.interrupt method. Including the comments from the interrupt method of the thread. Based on code comments from JDK documentation below is the behavior of the interrupt method. If a thread is blocked in an invocation of the wait, join or sleep method the thread will receive a Interrupted exception to continue to the exception handling block of the thread.

If a thread is blocked in an IO operation. The underlying IO channel will be closed and the thread will be interrupted. Interrupting a not alive thread has no effect.

Now after reading this it looks like the thread will be killed just by calling the interrupt method. But it does not work that way. If we write our code like below there is no way for the process to interrupt the thread.

The thread code below will keep continuing and will ignore the interrupt signal as long as the //do some operation block does not involve handling IO operations.

When operating with thread it is always safe to use a boolean flag to give the underlying thread or runnable breathing time and graciously have a calm death. Hence the introduction of Simple Thread example given below which shows how to gracefully exit threads.

In order for the above method to be effective we need to add the below interrupt method to the SimpleThreadPool

Disclaimer: Unless properly developed a java thread will leak and never die until the JVM quits even if the interrupt method is called.



Comments Section

Feel free to comment on the post but keep it clean and on topic.