Introduction to Java InterruptedException
InterruptedException phenomenon occurs when a thread that might be sleeping, waiting, or is occupied and that is interrupted before or at the time of some activity that is being executed. Sometimes a method might want to test whether a current thread has been interrupted or not. If it has been interrupted, then it will be throwing an exception immediately. Otherwise, it will be working the way it was working. In this topic, we are going to learn about Java InterruptedException.
Syntax
In order to use the exception, you have to use the following syntax:
if(Thread.interrupted()) // Clears interrupted status!
throw new InterruptedException();
Here the method InterruptedException() creates an InterruptedException with no detailed message in it as a parameter.
But if it is thrown like InterruptedException(String s) then it creates an InterruptedException with some specific detail message. In this method s is the detailed message.
How InterruptedException work in Java?
Here we will discuss the workflow of InterruptedException. Here in multi-threaded code, threads can often block; the thread pauses execution until some external condition is met, such as:
- when a lock is released
- or another thread completes an operation
- and also, some I/O operation completes
Over here threads can be interrupted. When an interrupt occurs, it stops the thread to do the regular kind of work they are doing. But the exact response to the specified interrupt depends upon the thread’s state and then how the thread will be implemented as below:
4.8 (8,411 ratings)
View Course
We will have a thread which can be used to block threads or earlier threads which were present. When this is caught it throws the InterruptedException. If there is no issue and there is no earlier thread then the thread continues with its work. When the thread comes across an exception it sets the thread’s interrupted status to true. The thread will poll to the method checkInterrupted() at regular intervals. This is the preferred way in which the thread is expected to work. Once the process is completed then there is a cleanup activity which takes place. After clean up the execution is then stopped. It throws the InterruptedException if any and if not it continues with its normal flow of execution.
In the above process if there is an interruption the process is not supposed to closed the thread immediately. This is because it will be in the middle of some computation which will always be happening and hence it must wait.
Constructors
Constructors are Java objects which help in initializing a newly created object or method. It is a Java instance which does not have any return type. As this is supposed to initialize the object it has the same name as the class to which it belongs. As a result, whenever the object is called contructors are called automatically and are initialized. Below is a constructor method.
InterruptedException()
Here, this method creates an exception with no message in it. An instance of the InterruptedException class is being created over here. In this constructor the message parameter is being set as null.
Example:
public InterruptedException() InterruptedException(String s)
In this method of InterruptedException class, the parameter is being used as a specified message in the format of string. Here the string parameter explains the name of the class that threw the error.
Example on InterruptedException
Now we will have a look at an example where a thread is being interrupted:
// Java Program to check how
// interrupt() method works
// simultaneously while a thread stops working
class CheckInterruption extends Thread {
public void run()
{
try {
Thread.sleep(2000);
System.out.println("We are checking Interrupted Exception");
}
catch (InterruptedException e) {
throw new RuntimeException("Thread is" + "interrupted");
}
}
public static void main(String args[])
{
CheckInterruption t1 = new CheckInterruption();
t1.start();
try {
t1.interrupt();
}
catch (Exception e) {
System.out.println("Exception handled");
}
}
}
Output:
The above code helps us in understanding the concept of Interrupted Exception. We have a class CheckInterruption which extends the Thread class of Java. It then looks for the exception in try block. If there is any exception, then it is caught in the catch block and output is displayed as in catch block. This is the case in our example where the interruption is caught and necessary output is displayed. But the program is not completed as the catch block calls the Exception () method present in Java. Let us now check an example where the exception is caught, and then the next thread starts.
class CheckInterruptingThread2 extends Thread{
public void run(){
try{ Thread.sleep(1000);
System.out.println("task");
}catch(InterruptedException e){
System.out.println("Exception is handled "+e); }
System.out.println("thread is now in running state...");
}
public static void main(String args[]){
CheckInterruptingThread2 t1=new CheckInterruptingThread2();
t1.start();
t1.interrupt();
}
}
Output:
The above program uses a class which is again extending the Thread class in Java. In the try() block we make the thread sleep for sometime and then catch block catches the exception when it is encountered. Once it is handled the message is printed and then the interrupt() method is called after which the next thread moves to the running state. The same is displayed after the method call is finished and the thread starts working.
How to avoid InterruptedException?
The solution to this exception is you can stop making the use of thread.sleep() method. Instead of this method the more efficient method will be SystemClock.sleep() method. Another replacement for the above mentioned method can be using TimeCOunter which will depend on the logic and code where it is being used. This can also me an optimal solution.
If at all you would still like to make use of thread.sleep() then it should be used as below.
try {
Thread.sleep();
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); /* this line will see to it that Thread.interrupted() always returns true */
throw new RuntimeException(e);
}
Conclusion – Java InterruptedException
As the word exception suggests, it is a state which can be checked and allowed to pass in some cases. InterruptedException happens when a thread waits or sleeps, and other threads are interrupted and cannot proceed further. We can handle this exception by either using proper try catch blocks or by avoiding the usage of sleep() method.
Recommended Articles
This is a guide to Java InterruptedException. Here we discuss How InterruptedException works in Java and Example with the codes and outputs. You may also have a look at the following articles to learn more –