What does java.lang.Thread.interrupt() do?

JavaMultithreading

Java Problem Overview


Could you explain what java.lang.Thread.interrupt() does when invoked?

Java Solutions


Solution 1 - Java

Thread.interrupt() sets the interrupted status/flag of the target thread. Then code running in that target thread MAY poll the interrupted status and handle it appropriately. Some methods that block such as Object.wait() may consume the interrupted status immediately and throw an appropriate exception (usually InterruptedException)

Interruption in Java is not pre-emptive. Put another way both threads have to cooperate in order to process the interrupt properly. If the target thread does not poll the interrupted status the interrupt is effectively ignored.

Polling occurs via the Thread.interrupted() method which returns the current thread's interrupted status AND clears that interrupt flag. Usually the thread might then do something such as throw InterruptedException.

EDIT (from Thilo comments): Some API methods have built in interrupt handling. Of the top of my head this includes.

  • Object.wait(), Thread.sleep(), and Thread.join()
  • Most java.util.concurrent structures
  • Java NIO (but not java.io) and it does NOT use InterruptedException, instead using ClosedByInterruptException.

EDIT (from @thomas-pornin's answer to exactly same question for completeness)

Thread interruption is a gentle way to nudge a thread. It is used to give threads a chance to exit cleanly, as opposed to Thread.stop() that is more like shooting the thread with an assault rifle.

Solution 2 - Java

What is interrupt ? > An interrupt is an indication to a > thread that it should stop what it is > doing and do something else. It's up > to the programmer to decide exactly > how a thread responds to an interrupt, > but it is very common for the thread > to terminate. >

How is it implemented ? > The interrupt mechanism is implemented > using an internal flag known as the > interrupt status. Invoking > Thread.interrupt sets this flag. When > a thread checks for an interrupt by > invoking the static method > Thread.interrupted, interrupt status > is cleared. The non-static > Thread.isInterrupted, which is used by > one thread to query the interrupt > status of another, does not change the > interrupt status flag.

Quote from Thread.interrupt() API:

> Interrupts this thread. First the > checkAccess method of this thread is > invoked, which may cause a > SecurityException to be thrown. > > If this thread is blocked in an > invocation of the wait(), wait(long), > or wait(long, int) methods of the > Object class, or of the join(), > join(long), join(long, int), > sleep(long), or sleep(long, int), > methods of this class, then its > interrupt status will be cleared and > it will receive an > InterruptedException. > > If this thread is blocked in an I/O > operation upon an interruptible > channel then the channel will be > closed, the thread's interrupt status > will be set, and the thread will > receive a ClosedByInterruptException. > > If this thread is blocked in a > Selector then the thread's interrupt > status will be set and it will return > immediately from the selection > operation, possibly with a non-zero > value, just as if the selector's > wakeup method were invoked. > > If none of the previous conditions > hold then this thread's interrupt > status will be set.

Check this out for complete understanding about same :

http://download.oracle.com/javase/tutorial/essential/concurrency/interrupt.html

Solution 3 - Java

If the targeted thread has been waiting (by calling wait(), or some other related methods that essentially do the same thing, such as sleep()), it will be interrupted, meaning that it stops waiting for what it was waiting for and receive an InterruptedException instead.

It is completely up to the thread itself (the code that called wait()) to decide what to do in this situation. It does not automatically terminate the thread.

It is sometimes used in combination with a termination flag. When interrupted, the thread could check this flag, and then shut itself down. But again, this is just a convention.

Solution 4 - Java

For completeness, in addition to the other answers, if the thread is interrupted before it blocks on Object.wait(..) or Thread.sleep(..) etc., this is equivalent to it being interrupted immediately upon blocking on that method, as the following example shows.

public class InterruptTest {
    public static void main(String[] args) {

        Thread.currentThread().interrupt();

        printInterrupted(1);

        Object o = new Object();
        try {
            synchronized (o) {
                printInterrupted(2);
                System.out.printf("A Time %d\n", System.currentTimeMillis());
                o.wait(100);
                System.out.printf("B Time %d\n", System.currentTimeMillis());
            }
        } catch (InterruptedException ie) {
            System.out.printf("WAS interrupted\n");
        }
        System.out.printf("C Time %d\n", System.currentTimeMillis());

        printInterrupted(3);

        Thread.currentThread().interrupt();

        printInterrupted(4);

        try {
            System.out.printf("D Time %d\n", System.currentTimeMillis());
            Thread.sleep(100);
            System.out.printf("E Time %d\n", System.currentTimeMillis());
        } catch (InterruptedException ie) {
            System.out.printf("WAS interrupted\n");
        }
        System.out.printf("F Time %d\n", System.currentTimeMillis());

        printInterrupted(5);

        try {
            System.out.printf("G Time %d\n", System.currentTimeMillis());
            Thread.sleep(100);
            System.out.printf("H Time %d\n", System.currentTimeMillis());
        } catch (InterruptedException ie) {
            System.out.printf("WAS interrupted\n");
        }
        System.out.printf("I Time %d\n", System.currentTimeMillis());

    }
    static void printInterrupted(int n) {
        System.out.printf("(%d) Am I interrupted? %s\n", n,
                Thread.currentThread().isInterrupted() ? "Yes" : "No");
    }
}

Output:

$ javac InterruptTest.java 

$ java -classpath "." InterruptTest
(1) Am I interrupted? Yes
(2) Am I interrupted? Yes
A Time 1399207408543
WAS interrupted
C Time 1399207408543
(3) Am I interrupted? No
(4) Am I interrupted? Yes
D Time 1399207408544
WAS interrupted
F Time 1399207408544
(5) Am I interrupted? No
G Time 1399207408545
H Time 1399207408668
I Time 1399207408669

Implication: if you loop like the following, and the interrupt occurs at the exact moment when control has left Thread.sleep(..) and is going around the loop, the exception is still going to occur. So it is perfectly safe to rely on the InterruptedException being reliably thrown after the thread has been interrupted:

while (true) {
    try {
        Thread.sleep(10);
    } catch (InterruptedException ie) {
        break;
    }
}

Solution 5 - Java

Thread interruption is based on flag interrupt status. For every thread default value of interrupt status is set to false. Whenever interrupt() method is called on thread, interrupt status is set to true.

  1. If interrupt status = true (interrupt() already called on thread), that particular thread cannot go to sleep. If sleep is called on that thread interrupted exception is thrown. After throwing exception again flag is set to false.
  2. If thread is already sleeping and interrupt() is called, thread will come out of sleeping state and throw interrupted Exception.

Solution 6 - Java

Thread.interrupt() sets the interrupted status/flag of the target thread to true which when checked using Thread.interrupted() can help in stopping the endless thread. Refer http://www.yegor256.com/2015/10/20/interrupted-exception.html

Solution 7 - Java

Thread.interrupt() method sets internal 'interrupt status' flag. Usually that flag is checked by Thread.interrupted() method.

By convention, any method that exists via InterruptedException have to clear interrupt status flag.

Solution 8 - Java

An interrupt is an indication to a thread that it should stop what it is doing and do something else. It's up to the programmer to decide exactly how a thread responds to an interrupt, but it is very common for the thread to terminate. A very good referance: https://docs.oracle.com/javase/tutorial/essential/concurrency/interrupt.html

Solution 9 - Java

public void interrupt()

Interrupts this thread.

Unless the current thread is interrupting itself, which is always permitted, the checkAccess method of this thread is invoked, which may cause a SecurityException to be thrown.

If this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.

If this thread is blocked in an I/O operation upon an interruptible channel then the channel will be closed, the thread's interrupt status will be set, and the thread will receive a ClosedByInterruptException.

If this thread is blocked in a Selector then the thread's interrupt status will be set and it will return immediately from the selection operation, possibly with a non-zero value, just as if the selector's wakeup method were invoked.

If none of the previous conditions hold then this thread's interrupt status will be set.

Interrupting a thread that is not alive need not have any effect.

Throws: SecurityException - if the current thread cannot modify this thread

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiononeatView Question on Stackoverflow
Solution 1 - JavaMike QView Answer on Stackoverflow
Solution 2 - JavaYoKView Answer on Stackoverflow
Solution 3 - JavaThiloView Answer on Stackoverflow
Solution 4 - JavaEvgeni SergeevView Answer on Stackoverflow
Solution 5 - Javaakash GView Answer on Stackoverflow
Solution 6 - JavaSanchi GirotraView Answer on Stackoverflow
Solution 7 - JavaAnatolii ShubaView Answer on Stackoverflow
Solution 8 - JavaAdiView Answer on Stackoverflow
Solution 9 - JavaAjeet GangaView Answer on Stackoverflow