Sotirios-Efstathios Maneas

About Sotirios-Efstathios Maneas

Sotirios-Efstathios (Stathis) Maneas is a postgraduate student at the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. His main interests include distributed systems, web crawling, model checking, operating systems, programming languages and web applications.

java.lang.InterruptedException – How to handle InterruptedException

In this example we will discuss about InterruptedException in Java. This exception is thrown when a thread is interrupted. The thread could be in either waiting, sleeping or running state and this exception can be thrown either before or during a thread’s activity.

This exception extends the Exception class and thus, can be classified as a checked exception. Checked exceptions must be explicitly declared in a method’s or constructor’s throw clause.

Finally, the InterruptedException exists since the 1.0 version of Java.

 

The Structure of InterruptedException

Constructors

  • InterruptedException()
  • Creates an instance of the InterruptedException class, setting null as its message.

  • InterruptedException(String s)
  • Creates an instance of the InterruptedException class, using the specified string as message. The string argument indicates the name of the class that threw the error.

The InterruptedException in Java

A sample example where a thread is being interrupted is shown below:

SampleThread.java:

import java.util.concurrent.TimeUnit;

public class SampleThread extends Thread {
	public SampleThread() {
		super();
		System.out.println("An instance of the " + SampleThread.class + " class was created!");
	}
	
	@Override
	public void run() {
		try {
			/* Sleep for some seconds. */
			TimeUnit.SECONDS.sleep(10);
		}
		catch(InterruptedException ex) {
			System.err.println("An InterruptedException was caught: " + ex.getMessage());
		}
	}
}

First, we define the SampleThread class, which extends the Thread class and overrides its run method.

InterruptedExceptionExample.java:

public class InterruptedExceptionExample {
	public static void main(String[] args) throws InterruptedException {
		// Create a new thread.
		Thread thread = new SampleThread();
		
		//Start the thread's execution.
		thread.start();
		
		//Interrupt the thread.
		thread.interrupt();
		
		//Join the thread.
		thread.join();
	}
}

Then, we create an instance of the SampleThread and interrupt it during its execution. A sample execution is shown below:

An instance of the class main.java.SampleThread class was created!
An InterruptedException was caught: sleep interrupted

More about the InterruptedException in Java

As we already mentioned, every thread has a boolean flag that represents its interrupted status. Initially, this status is set to false for every thread. If a thread is interrupted during an interruptible method such as join or sleep, it will unblock and throw an InterruptedException. In any other case, the thread’s interruption will only update the thread’s interrupted status. A thread can test if its interrupted using one of the following methods:

Notice that the 2nd method does not affect the interrupted status of the thread, in contrast to the 1st method which clears the interrupted status of the calling thread. A second call to the Thread::interrupted() method returns false, unless the calling thread was interrupted again.

How to deal with the InterruptedException

  • The most simple strategy is to throw the InterruptedException to the upper layer of the calling stack and let the upper layer handle it.
  • Another strategy is to catch the InterruptedException, perform some memory cleanup and then, propagate the exception to the upper layer of the calling stack.
  • Moreover, for those cases where a method cannot throw an InterruptedException, you can use the following method, in order to interrupt the current thread:
  •         Thread.currentThread().interrupt();
            

    This approach can be very useful, because once a Thread catches an InterruptedException, its interrupted status is cleared and instead of ignoring the exception, we restore the interrupted status of the current Thread.

  • Finally, never ignore or swallow the InterruptedException.

Download the Eclipse Project

The Eclipse project of this example: InterruptedExceptionExample.zip.

 
This was a tutorial about InterruptedException in Java.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.
Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close