Java InterruptedException

Introduction

InterruptedException in Java is a checked exception that occurs when a thread is interrupted while it is waiting, sleeping, or otherwise occupied. It is part of Java’s concurrency mechanisms.

Table of Contents

  1. What is InterruptedException?
  2. Common Causes
  3. Handling InterruptedException
  4. Examples of InterruptedException
  5. Conclusion

1. What is InterruptedException?

InterruptedException is thrown when a thread that is waiting, sleeping, or blocked is interrupted. It helps manage thread interruptions and ensures that threads can respond to interruption requests.

2. Common Causes

  • A thread is sleeping or waiting, and another thread interrupts it using Thread.interrupt().
  • A blocked thread on I/O or synchronization is interrupted.

3. Handling InterruptedException

To handle InterruptedException:

  • Catch the exception in a try-catch block.
  • Decide whether to stop the thread, retry the operation, or perform cleanup.
  • Preserve the interrupted status of the thread if needed.

4. Examples of InterruptedException

Example: Handling InterruptedException in a Sleeping Thread

This example demonstrates how to handle InterruptedException when a thread is interrupted during sleep.

public class InterruptedExceptionExample { public static void main(String[] args) { Thread thread = new Thread(() -> { try { System.out.println("Thread is going to sleep."); Thread.sleep(5000); System.out.println("Thread woke up naturally."); } catch (InterruptedException e) { System.out.println("Thread was interrupted."); // Optionally, preserve the interrupted status Thread.currentThread().interrupt(); } }); thread.start(); try { Thread.sleep(2000); // Main thread sleeps for 2 seconds } catch (InterruptedException e) { e.printStackTrace(); } thread.interrupt(); // Interrupts the sleeping thread } } 

Output:

Thread is going to sleep. Thread was interrupted. 

5. Conclusion

InterruptedException in Java is crucial for managing thread interruptions in concurrent programming. By properly handling this exception, you can ensure that threads respond appropriately to interruptions, leading to more robust and responsive applications.

Leave a Comment

Scroll to Top