Java Thread interrupt explanation with examples

Java Thread Interrupt

 248 total views

In this comprehensive guide, we will learn about How Java Thread interrupt works and the relevance of interrupt(), interrupted(), and the InterruptedException.

What is Java Thread Interrupt?

This is a process in which a Thread A can ask another Thread B to stop its execution using the below method.

threadB.interrupt();

Obviously to call the interrupt method Thread A must have reference of Thread B.

Why do we need Thread interruption?

There can be many usecases for thread interruption like

  1. Thread is taking a longer time than expected to perform any operation, for example, an I/O operation.
  2. Thread is waiting or sleeping for a long time for a resource.
  3. In a time-sensitive application where web-services must response in specified seconds and etc.

What actually happens?

Always remember One Thread cannot stop or terminate the execution of another thread.

It can only make a request for the termination using the interrupt method. Now its completely on the programmer to decide what to do on interruption request.

The most common use-case is to terminate the thread.

Java thread Interrupt example

Keeping the above points in mind lets create a thread and let’s interrupt it from the main thread.

Below thread will print Iteration counts from 1 to 10.

DemoThread.java

public class DemoThread implements Runnable {

	@Override
	public void run() {
		for (int i = 1; i <= 10; i++) {
			System.out.println("Iteration count " + i);
		}
	}
}

Test.java

public class Test {
	public static void main(String[] args) throws InterruptedException {
		Thread demoThread = new Thread(new DemoThread());
		demoThread.start();
		demoThread.interrupt();
	}
}

Output:

Iteration count 1
Iteration count 2
Iteration count 3
Iteration count 4
Iteration count 5
Iteration count 6
Iteration count 7
Iteration count 8
Iteration count 9
Iteration count 10

As you can see, in the main method

  1. The main thread starts the demo thread.
  2. It immediately calls interrupt on demo thread.
  3. Demo thread is not interrupted and it has printed all the iteration counts.

From the above example, we can clearly see that main thread requests for an interruption to demoThread and the request was not respected.

Respect thread interrupt request

We have clearly seen that I have not written any code in the demo thread’s run method that will honor the interrupt request.

So lets make some changes in run() method.

Here we will look at the two approaches for providing interrupt support.

Approach 1: Using Thread.sleep() method

public class DemoThread implements Runnable {
	@Override
	public void run() {
		for (int i = 1; i <= 10; i++) {
			System.out.println("Iteration count " + i);
			try {
				Thread.sleep(10);
			} catch (InterruptedException e) {
				System.out.println("This thread was interrupted");
				System.out.println("Terminating Demo Thread!!!");
				return;
			}
		}
	}
}

Output:

Iteration count 1
This thread was interrupted
Terminating Demo Thread!!!

Most of the Java thread methods that stop/block the normal thread execution support thread interruption and throw the interruptedException.

Hence In this approach, I am making my thread to sleep for 10ms and on interruption, it throws interruptedExcepion.

Then I have caught the exception in the run method and terminated the execution using the return statement.

But you might be thinking why should I use any of these methods as part of the solution as it does not look clean so let’s look at the second approach.

Approach 2: Use Thread.interrupted()

public class DemoThread implements Runnable {
	@Override
	public void run() {
		for (int i = 1; i <= 10; i++) {
			System.out.println("Iteration count " + i);
			if (Thread.interrupted())
			{
				System.out.println("This thread was interrupted");
				System.out.println("Terminating Demo Thread!!!");
				return;
			}
		}
	}
}

Output:

Iteration count 1
This thread was interrupted
Terminating Demo Thread!!!

Java multithreading framework provides a Thread.interrupted() method to check if the current thread was interrupted by any other thread.

Using this method you can simply terminate the execution by

  • return statement
  • Throwing InterruptedException.

Internal implementation

As we have learned how to interrupt a thread and also how to support interruption from user-defined threads let’s talk about the internal implementation a bit.

Interrupt status flag

The interrupt mechanism is implemented using the interrupt status flag.

  1. Thread A calls the threadB.interrupt() method which sets this flag to true.
  2. Thread B keeps on executing normally until we check the interrupt flag’s status using Thread.interrupted() method.
  3. Once we check the flag’s status we stop the execution.
  4. Once Thread.interrupted() is called it clears the interrupt status flag’s value.

All the other methods like sleep, join and wait also clear this flag’s value.

Conclusion

In conclusion, I would say one thread can only request another thread for interruption and it solely depends on the programmer how he wants to handle the interruption.

  • Firstly, the developer can handle the exception internally and keep on executing its task.
  • Secondly, he or she may interrupt the current execution and perform something else.
  • Thirdly and the most common one is to terminate the execution or raise an Interrupted exception and let the calling thread handle it.

Leave a Reply

Your email address will not be published. Required fields are marked *