1. Introduction
In this tutorial, we'll explore Java's InterruptedException. First, we'll quickly go through the life cycle of a thread with an illustration. Next, we'll see how working in multithreaded applications can potentially cause an InterruptedException. Finally, we will see how to handle this exception.
2. Multithreading Basics
Before discussing interrupts, let's review multithreading. Multithreading is a process of executing two or more threads simultaneously. A Java application starts with a single thread – called the main thread – associated with the main() method. This main thread can then start other threads.
Threads are lightweight, which means that they run in the same memory space. Hence, they can easily communicate among themselves. Let's take a look at the life cycle of a thread:
As soon as we create a new thread, it’s in the NEW state. It remains in this state until the program starts the thread using the start() method.
Calling the start() method on a thread puts it in the RUNNABLE state. Threads in this state are either running or ready to run.
When a thread is waiting for a monitor lock and is trying to access code that is locked by some other thread, it enters the BLOCKED state.
A thread can be put in the WAITING state by various events, such as a call to the wait() method. In this state, a thread is waiting for a signal from another thread.
When a thread either finishes execution or terminates abnormally, it'll wind up in the TERMINATED state. Threads can be interrupted, and when a thread is interrupted, it will throw InterruptedException.
In the next sections, we'll see InterruptedException in detail and learn how to respond to it.
3. What Is An InterruptedException?
An InterruptedException is thrown when a thread is interrupted while it's waiting, sleeping, or otherwise occupied. In other words, some code has called the interrupt() method on our thread. It's a checked exception, and many blocking operations in Java can throw it.
3.1. Interrupts
The purpose of the interrupt system is to provide a well-defined framework for allowing threads to interrupt tasks (potentially time-consuming ones) in other threads. A good way to think about interruption is that it doesn't actually interrupt a running thread — it just requests that the thread interrupt itself at the next convenient opportunity.
3.2. Blocking and Interruptible Methods
Threads may block for several reasons: waiting to wake up from a Thread.sleep(), waiting to acquire a lock, waiting for I/O completion, or waiting for the result of a computation in another thread, among others.
The InterruptedException is usually thrown by all blocking methods so that it can be handled and the corrective action can be performed. There are several methods in Java that throw InterruptedException. These include Thread.sleep(), Thread.join(), the wait() method of the Object class, and put() and take() methods of BlockingQueue, to name a few.
3.3. Interruption Methods in Threads
Let's have a quick look at some key methods of the Thread class for dealing with interrupts:
public void interrupt() { ... }
public boolean isInterrupted() { ... }
public static boolean interrupted() { ... }
Thread provides the interrupt() method for interrupting a thread, and to query whether a thread has been interrupted, we can use the isInterrupted() method. Occasionally, we may wish to test whether the current thread has been interrupted and if so, to immediately throw this exception. Here, we can use the interrupted() method:
if (Thread.interrupted()) {
throw new InterruptedException();
}
3.4. The Interrupt Status Flag
The interrupt mechanism is implemented using a flag known as the interrupt status. Each thread has a boolean property that represents its interrupted status. Invoking Thread.interrupt() sets this flag. When a thread checks for an interrupt by invoking the static method Thread.interrupted(), the interrupt status is cleared.
To respond to interrupt requests, we must handle InterruptedException. We'll see how to do just that in the next section.
4. How to Handle an InterruptedException
It's important to note that thread scheduling is JVM-dependent. This is natural, as JVM is a virtual machine and requires the native operating system resources to support multithreading. Hence, we can't guarantee that our thread will never be interrupted.
An interrupt is an indication to a thread that it should stop what it's doing and do something else. More specifically, if we're writing some code that will be executed by an Executor or some other thread management mechanism, we need to make sure that our code responds promptly to interrupts. Otherwise, our application may lead to a deadlock.
There are few practical strategies for handling InterruptedException. Let's take a look at them.
4.1. Propagate the InterruptedException
We can allow the InterruptedException to propagate up the call stack, for example, by adding a throws clause to each method in turn and letting the caller determine how to handle the interrupt. This can involve our not catching the exception or catching and rethrowing it. Let's try to achieve this in an example:
public static void propagateException() throws InterruptedException {
Thread.sleep(1000);
Thread.currentThread().interrupt();
if (Thread.interrupted()) {
throw new InterruptedException();
}
}
Here, we are checking whether the thread is interrupted and if so, we throw an InterruptedException. Now, let's call the propagateException() method:
public static void main(String... args) throws InterruptedException {
propagateException();
}
When we try to run this piece of code, we'll receive an InterruptedException with the stack trace:
Exception in thread "main" java.lang.InterruptedException
at com.baeldung.concurrent.interrupt.InterruptExample.propagateException(InterruptExample.java:16)
at com.baeldung.concurrent.interrupt.InterruptExample.main(InterruptExample.java:7)
Although this is the most sensible way to respond to the exception, sometimes we can't throw it — for instance, when our code is a part of a Runnable. In this situation, we must catch it and restore the status. We'll see how to handle this scenario in the next section.
4.2. Restore the Interrupt
There are some cases where we can't propagate InterruptedException. For example, suppose our task is defined by a Runnable or overriding a method that doesn't throw any checked exceptions. In such cases, we can preserve the interruption. The standard way to do this is to restore the interrupted status.
We can call the interrupt() method again (it will set the flag back to true) so that the code higher up the call stack can see that an interrupt was issued. For example, let's interrupt a thread and try to access its interrupted status:
public class InterruptExample extends Thread {
public static Boolean restoreTheState() {
InterruptExample thread1 = new InterruptExample();
thread1.start();
thread1.interrupt();
return thread1.isInterrupted();
}
}
And here's the run() method that handles this interrupt and restores the interrupted status:
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); //set the flag back to true
} }
Finally, let's test the status:
assertTrue(InterruptExample.restoreTheState());
Although Java exceptions cover all the exceptional cases and conditions, we might want to throw a specific custom exception unique to the code and business logic. Here, we can create our custom exception to handle the interrupt. We'll see it in the next section.
4.3. Custom Exception Handling
Custom exceptions provide the flexibility to add attributes and methods that are not part of a standard Java exception. Hence, it's perfectly valid to handle the interrupt in a custom way, depending on the circumstances.
We can complete additional work to allow the application to handle the interrupt request gracefully. For instance, when a thread is sleeping or waiting on an I/O operation, and it receives the interrupt, we can close any resources before terminating the thread.
Let’s create a custom checked exception called CustomInterruptedException:
public class CustomInterruptedException extends Exception {
CustomInterruptedException(String message) {
super(message);
}
}
We can throw our CustomInterruptedException when the thread is interrupted:
public static void throwCustomException() throws Exception {
Thread.sleep(1000);
Thread.currentThread().interrupt();
if (Thread.interrupted()) {
throw new CustomInterruptedException("This thread was interrupted");
}
}
Let's also see how we can check whether the exception is thrown with the correct message:
@Test
public void whenThrowCustomException_thenContainsExpectedMessage() {
Exception exception = assertThrows(CustomInterruptedException.class, () -> InterruptExample.throwCustomException());
String expectedMessage = "This thread was interrupted";
String actualMessage = exception.getMessage();
assertTrue(actualMessage.contains(expectedMessage));
}
Similarly, we can handle the exception and restore the interrupted status:
public static Boolean handleWithCustomException() throws CustomInterruptedException{
try {
Thread.sleep(1000);
Thread.currentThread().interrupt();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new CustomInterruptedException("This thread was interrupted...");
}
return Thread.currentThread().isInterrupted();
}
We can test the code by checking the interrupted status to make sure it returns true:
assertTrue(InterruptExample.handleWithCustomException());
5. Conclusion
In this tutorial, we saw different ways to handle the InterruptedException. If we handle it correctly, we can balance the responsiveness and robustness of the application. And, as always, the code snippets used here are available over on GitHub.
The post How to Handle InterruptedException in Java first appeared on Baeldung.