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

Restoring Interrupt Status in catch Blocks

Using Thread.currentThread().interrupt() to preserve interruption when catching InterruptedException.

Restoring Interrupt Status in catch Blocks

You'll learn why and how to preserve a thread's interrupted status when catching InterruptedException.

The Problem: Swallowing Interruption Signals

When you catch an InterruptedException, Java automatically clears the thread's interrupt flag. If you simply catch the exception and do nothing, you've effectively erased important information that higher-level code might need. It's like someone tapping you on the shoulder to get your attention, but you ignore them and don't tell anyone else they wanted to talk.

The Solution: Restore the Flag

After catching InterruptedException, immediately call Thread.currentThread().interrupt() to restore the interrupted status:

try {
    Thread.sleep(1000);
} catch (InterruptedException e) {
    // Restore the interrupted status
    Thread.currentThread().interrupt();
    // Then handle appropriately (log, cleanup, etc.)
}

Why This Matters

Your code might be running inside a larger framework or library that checks the interrupt status to make shutdown decisions. By restoring the flag, you:

  1. Preserve the signal for code higher up the call stack
  2. Maintain proper interrupt semantics across your application
  3. Allow coordinated shutdown of thread pools and executors

Think of it like passing along an urgent message: even if you can't act on it immediately, you ensure the next person in line knows something important happened.

When to Restore

Restore the interrupt status whenever you catch InterruptedException but cannot fully handle the interruption (like terminating your task immediately). If your method doesn't throw InterruptedException, restoring the flag is your responsibility.

Key Takeaway: Always call Thread.currentThread().interrupt() in your catch (InterruptedException) block to preserve the interruption signal for higher-level code that might need to know the thread was interrupted.