Thread interruption in Java (ctd)

On the previous page, we looked at the basics of thread interruption in Java. On this page, we'll explore a few more details that we need to consider.

What if the interruptee isn't doing a blocking call?

In the above example, you may be thinking, "what if the call to interrupt() happens while the other thread is printing the message (rather than in the Thread.sleep() call)?". Well, it turns out not to matter in this case. If the interruptee is not in a blocking method, then:

So provided that the interrupted thread periodically calls a blocking call such as Thread.sleep(), the interruption mechanism still works.

What if the interrupted method isn't ever (or soon) going to call a blocking method like like sleep() or wait()? In this case:

To manually check for the interrupted flag, we call isInterrupted(). For example:

public void performLongCalculation() throws InterruptedException {
  for (int i = 0; i < PART_COUNT; i++) {
    if (isInterrupted())
      throw new InterruptedException();
    performPartOfCalculation();
  }
}

This technique is usually more useful when the thread is performing a combination of interruptible and non-interruptible calls. Otherwise, we can implement our own cancellation flag (typically via a volatile boolean).

How to handle InterruptedException?

A common piece of bad program design is to "micro-manage" InterruptedException (and indeed, exceptions in general), by catching it and "pretending nothing happened". But in a good design, like any exception, it should be dealt with cleanly. What exactly to do with InterruptedException can depend on the program and situation, of course, but as a rule of thumb:

An InterruptedException should cause the overall task to be cancelled.

This generally means: