How does Thread interrupt?

Thread class in Java has method interrupt() which usually stops the Thread from doing something and inform it to do something else. Generally speaking it diverts Thread to another direction. Note here for any Thread to interrupt it must support it’s own interruption, now let’s see why.

The interruption works with the help of internal flag of Thread named interrupt status. This status can be polled by code inside the Thread which check whether it’s interrupted or not. Ultimately the code inside run method should have code which can check whether thread interrupted or not by polling the interrupt status to interrupt Thread. On the other side method like Thread.sleep() internally poll the interrupt status and throw the InterruptedException immediately. Let’s check the following example,

class RunMe implements Runnable {

	@Override
	public void run() {
		System.out.println("Executing :"+Thread.currentThread().getName());
		try{
			for(int i = 1; i <= 5; i++) {
				System.out.println("Thread Sleeping for : "+i+&quot; Seconds&quot;);
				Thread.sleep(i*1000);
			}
		} catch (InterruptedException e) {
			System.out.println("Thread Interrupted.");
			return;//Return if thread is interrupted
		}
		System.out.println("Execution completed");
	}

}

public class InterruptDemo {

	public static void main(String[] args) {
		RunMe runMe = new RunMe();
		Thread t1 = new Thread(runMe);
		t1.start();
		try {
			Thread.sleep(1000);//Sleep main thread
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		t1.interrupt();
	}

}

In above example from Main thread we have called t1.interrupt() which will change the interrupt status of thread t1.Now as t1 has Thread.sleep() which internally poll the interrupt status and throw the InterruptedException by which we can simply return from the execution and we will have following output.

Executing :Thread-0
Thread Sleeping for : 1 Seconds
Thread Sleeping for : 2 Seconds
Thread Interrupted.

Note the last statement is not printed because of the return statement otherwise the interrupt will be ignored and we would have last statement in the output. Here once InterruptedException is thrown by Thread.sleep() the interrupt status of the Thread will be cleared.

Moreover, if Thread does not contain single line which can poll the interrupt status the interrupt is simply ignored. In Java threading becomes non-pre-emptive which simply means if higher priority task comes up and currently running thread can not poll the interrupt status than the interruption will be ignored by the current thread and the running thread will not be interrupted. Consider following example,

class RunMe implements Runnable {

	@Override
	public void run() {
		System.out.println("Executing :"+Thread.currentThread().getName());
		for(int i = 1; i <= 5; i++) {
			System.out.println("Inside loop for i = " +i);
		}
		System.out.println("Execution completed");
	}

}

public class InterruptDemo {

	public static void main(String[] args) {
		RunMe runMe = new RunMe();
		Thread t1 = new Thread(runMe);
		t1.start();
		t1.interrupt();//interrupt ignored
		System.out.println("Interrupt method called to interrupt t1");
	}

}

Note in above example that even if we have called interrupt method on thread t1 it still keeps executing as code inside thread is not capable of getting interrupt status or other way not capable of handling the interrupt status properly.

Interrupt method called to interrupt t1
Executing :Thread-0
Inside loop for i = 1
Inside loop for i = 2
Inside loop for i = 3
Inside loop for i = 4
Inside loop for i = 5
Execution completed

Some methods like Thread#sleep , Object#wait , Thread#join polls the interrupt status internally and fires the InterruptedException and clears the interrupt status.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s