Interrupting a thread in java

Often, someone will wish to somehow terminate a thread that is causing issues. These issues could be things such as blocking threads that prevent other threads from doing work, or something that is using a lot of CPU. While the JVM can be stopped and restarted, this is more invasive than just terminating the thread, if such a possibility exists.

There are many posts on the internet regarding the Thread.stop() method being dangerous and deprecated.

Once I researched this, the reason became clear.

If you stop a thread, java will dutifully stop it wherever it happens to be at that moment in time. If the thread to be stopped is actively manipulating data structures, this can be disastrous. Consider the case where variable A is to be incremented and variable B decremented. If only A is incremented, and then the thread is stopped, you may have a case where you have logically corrupt data and don’t notice it for awhile. By the time you do, more damage has been inflicted.

This is why Oracle recommends that you use a variable to indicate when a thread should stop. Of course, this means code changes. However, I would argue there are two reasons this is OK:

1) You must evaluate your application more closely, which is always a good thing
2) It forces you to evaluate where long running processes may exist, and provide you with an impetus to tune them while in the design phase. If you do this, you may never need to stop a thread.

If you do want to “stop” a thread, you can call the interrupt() method. However, keep in mind this only works if your code checks the Thread.interrupted state.

<%
try {
  Thread.sleep(1800 * 1000);
}
catch (Exception e) {
  out.println(e.getMessage());
}
%>
<%
java.util.Set threadSet = Thread.getAllStackTraces().keySet();
Thread[] threads = threadSet.toArray(new Thread[threadSet.size()]);
for ( Thread thread : threads)
  if ( thread.getName().equals("http-172.28.72.10-10180-1"))
    thread.interrupt();
%>

While the sample above is a nice shrink wrapped example, it works only because the sleep method checks the Thread.interrupted variable at regular intervals and will “stop” itself if it finds it has been interrupted.

If you change the code above from a sleep to a CPU churner, the page will continue to run to completion. To effectively use interrupt(), you have to plan to use it in your code. It is not a bail out for a thread run amok at 2AM.

Avoid it, and plan to allow your methods to be “stopped” (without using stop()), or interrupted. Regardless, you have to plan for it.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.