Thread interruption in Java

In our overview of thread methods, we saw various methods that throw InterruptedException.

Interruption is a mechanism whereby a thread that is waiting (or sleeping) can be made to prematurely stop waiting.

Incidentally, it is important not to confuse thread interruption with either software interrupts (where the CPU automatically interrupts the current instruction flow in order to call a registered piece of code periodically— as in fact happens to drive the thread scheduler) and hardware interrupts (where the CPU automatically performs a similar task in response to some hardware signal).

To illustrate interruption, let's consider again a thread that prints a message periodically. After printing the message, it sleeps for a couple of seconds, then repeats the loop:

Runnable r = new Runnable() {
  public void run() {
    try {
      while (true) {
        Thread.sleep(2000L);
        System.out.println("Hello, world!");
      }
    } catch (InterruptionException iex) {
      System.err.println("Message printer interrupted");
    }
  }
};
Thread thr = new Thread(r);
thr.start();

The InterruptedException is thrown by the Thread.sleep() method, and in fact by a few other core library methods that can "block", principally:

  • Object.wait(), part of the wait/notify mechanism;
  • Thread.join(), that makes the current thread wait for another thread to complete;
  • Proess.waitFor(), which lets us wait for an external process (started from our Java application) to terminate;
  • various methods in the Java 5 concurrency libraries, such as the tryLock() method of the Java 5 ReentrantLock class.

In general, InterruptedException is thrown when another thread interrupts the thread calling the blocking method. The other thread interrupts the blocking/sleeping thread by calling interrupt() on it:

thr.interrupt();

Provided that the thread or task calling sleep() (or whatever) has been implemented properly, the interruption mechanism can therefore be used as a way to cancel tasks.

Next: interruption during non-blocking calls and InterruptionException

On the next page, we'll look at a couple of further details that we haven't covered in the basics above:


If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.

Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.