Course contentsShow
← Java
Lesson 2601 of 2,87048. Concurrency FundamentalsFree lesson

Checking Interruption Status: isInterrupted()

Using isInterrupted() to check if a thread has been interrupted without clearing the flag.

Checking Interruption Status: isInterrupted()

What You'll Learn

You'll learn how to check whether a thread has been interrupted without clearing its interruption flag using the isInterrupted() method.

The Core Concept

When you call Thread.interrupt() on a thread, it sets an internal flag indicating that the thread has been interrupted. The isInterrupted() method allows you to check this flag at any time without affecting it—the flag remains set even after you check it.

This is crucial for scenarios where you want to poll the interruption status repeatedly or where you need to check the status before deciding how to proceed with cleanup or shutdown logic.

How isInterrupted() Works

The isInterrupted() method is an instance method called on a specific thread object:

Thread myThread = new Thread(() -> {
    while (!Thread.currentThread().isInterrupted()) {
        // Do work while not interrupted
        System.out.println("Working...");
    }
    // Thread detected interruption and is exiting
});

myThread.start();
Thread.sleep(100);
myThread.interrupt(); // Sets the flag

Think of isInterrupted() like checking a "stop requested" light on a control panel—you can look at it as many times as you want, and the light stays on until someone explicitly turns it off.

Non-Clearing Behavior

Unlike Thread.interrupted() (which clears the flag), isInterrupted() is read-only. You can call it multiple times and always get the same result:

Thread t = Thread.currentThread();
// Assume t is interrupted
t.isInterrupted(); // returns true
t.isInterrupted(); // still returns true
t.isInterrupted(); // still returns true

Key Takeaway: Use isInterrupted() to check a thread's interruption status without clearing the flag, making it ideal for cooperative cancellation patterns where you need to repeatedly test whether shutdown has been requested.