eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

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 – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

eBook – Java Concurrency – NPI (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

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.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

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.

eBook – Java Concurrency – NPI (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook Jackson – NPI EA – 3 (cat = Jackson)