Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Black Friday 2026 – NPI EA – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

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:

Threadlifecycle

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 a code block 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 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. Several methods in Java 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 throw this exception immediately. 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

Thread scheduling in Java is managed by the JVM and depends on the underlying operating system. However, a thread in Java can only be interrupted explicitly by a call to Thread.interrupt(), not by the JVM’s thread scheduling itself.

An interrupt signals a thread to pause its current activity and handle the interruption, typically by stopping or switching tasks. If our code runs within an Executor or another thread management mechanism, it’s crucial to handle interrupts properly to avoid issues like deadlocks.

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 allow adding 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 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.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Black Friday 2026 – NPI EA – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW