You are currently viewing Understanding InterruptedException in Java

Understanding InterruptedException in Java

  • Post author:
  • Post category:Java
  • Post comments:0 Comments
  • Post last modified:July 30, 2024

In Java programming, the InterruptedException is a checked exception that can occur when a thread is interrupted by another thread while it’s in a blocked state, typically waiting for an operation such as I/O, sleep, or waiting on a lock. This interruption mechanism allows threads to communicate with each other in a cooperative manner.

Why InterruptedException Occurs?

Java threads can be interrupted using the interrupt() method. When a thread calls interrupt() on another thread, it interrupts its execution by setting a flag. If the interrupted thread is currently executing a method that can throw InterruptedException, it will receive an InterruptedException to handle the interruption.

Handling InterruptedException

InterruptedException is a checked exception, which means it must be either caught or declared to be thrown in the method signature. Handling InterruptedException properly is important for maintaining the responsiveness and stability of your application.

Let’s dive into some examples to understand how to handle InterruptedException in different scenarios:

Example 1: Handling InterruptedException in Thread Sleep

public class SleepExample {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            try {
                Thread.sleep(5000); // Simulate some time-consuming operation
                System.out.println("Thread woke up after sleeping.");
            } catch (InterruptedException e) {
                System.out.println("Thread interrupted while sleeping.");
            }
        });

        thread.start();

        // Interrupt the thread after 2 seconds
        try {
            Thread.sleep(2000);
            thread.interrupt();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Output:

Thread interrupted while sleeping.

Example 2: Handling InterruptedException in Blocking I/O

import java.io.*;

public class InterruptedIOExample {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
                System.out.println("Waiting for user input...");
                String input = reader.readLine(); // Blocking I/O operation
                System.out.println("User input: " + input);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });

        thread.start();

        // Interrupt the thread after 2 seconds
        try {
            Thread.sleep(2000);
            thread.interrupt();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Output:

java.io.InterruptedIOException: null

Example 3: Handling InterruptedException in Object Wait

public class WaitNotifyExample {
    public static void main(String[] args) {
        final Object lock = new Object();

        Thread thread1 = new Thread(() -> {
            synchronized (lock) {
                try {
                    System.out.println("Thread 1 waiting...");
                    lock.wait(); // Wait indefinitely until notified
                    System.out.println("Thread 1 woke up.");
                } catch (InterruptedException e) {
                    System.out.println("Thread 1 interrupted while waiting.");
                }
            }
        });

        thread1.start();

        // Interrupt the waiting thread after 2 seconds
        try {
            Thread.sleep(2000);
            thread1.interrupt();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Output:

Thread 1 interrupted while waiting.

Conclusion

InterruptedException provides a mechanism for threads to gracefully handle interruptions from other threads. By properly handling this exception, you can ensure that your multi-threaded Java applications remain responsive and robust even in the presence of interruptions.

Leave a Reply