What does java.lang.Thread.interrupt() do?
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()
, andThread.join()
- Most
java.util.concurrent
structures - Java NIO (but not java.io) and it does NOT use
InterruptedException
, instead usingClosedByInterruptException
.
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.
Understanding the usage of Thread.interrupt()
This is a technique to keep the thread available for interruption.
Thread.interrupted() :
checks whether present thread (itself) was interrupted by some other thread and clears the interrupted status flag. So it asks itself whether I was interrupted by someone to exit from what I was doing while I was performing a BIG BIG task and not listening to someone.
Imagine what would have happened if that thing was not done.
Suppose one iteration of heavyCrunch()
takes 1 min worth of time. So n iterations will take n minutes.
Now suppose after starting the program you decide that you want to exit the program and terminate the program gracefully. So you interrupt the thread that is doing the heavy crunch.
BUT the thread is unknown of the fact that you have interrupted it as it is not checking for the interrupt status. So the program will not end until N Minutes have not completed and you will have to wait for long time.
So to gracefully terminate the thread, it should always keep checking the interrupt status to respond if someone else has requested interruption.
What happens when you invoke a thread's interrupt()?
Judging by your previous questions, I assume you are interested in Java's behavior.
In Java, an InterruptedException
will be thrown if the thread is currently blocking. If the thread is not blocking, the exception will not be thrown.
For more information, look here:
JavaDocs
For .NET languages, a ThreadInterruptedException
will be thrown if the thread is currently blocking. If the thread isn't blocking the exception will not be thrown until the thread blocks.
Please tag your question with the language you want an answer for.
When an Thread.interrupt() is called on some thread, what happens?
The target thread is "interrupted". Mostly, a flag is set in that thread, which the thread can look at (with Thread.interrupted()
). If the target thread was currently blocked on some I/O or Object.wait()
, then it is awakened with, respectively, an InterruptedIOException
or an InterruptedException
.
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()
, which is more like shooting the thread with an assault rifle.
How the main thread sleep/interrupt works in following code
Interruption is a polite request to stop: a Thread is under no obligation to stop.
It's like the Robin Williams joke about what police in the UK say when you commit a crime:
Stop! Or I'll say stop again!
Also, interrupting a thread doesn't cause an InterruptedException
to be thrown: it merely sets a flag on the thread. If something (like Thread.sleep
) checks this flag, and finds that it is set, it may then throw an InterruptedException
; but the flag and exception are two orthogonal ways of indicating interruption.
As such:
- On the first execution, you sleep for 3 seconds, then set the interrupted flag, and the loop body finishes normally.
- On the second execution, you ask to sleep for 3 seconds, but
Thread.sleep
detects the interrupted flag, and throws the exception.
Who is calling the Java Thread interrupt() method if I'm not?
The Thread interrupt mechanism is the preferred way to get a (cooperating) thread to respond a request to stop what it is doing. Any thread (including the thread itself I think) could call interrupt()
on a Thread.
In practice, the normal use-cases for interrupt()
involve some kind of framework or manager telling some worker thread to stop what they are doing. If the worker thread is "interrupt aware" it will notice that it has been interrupted via an exception, or by periodically checking its interrupted flag. On noticing that it has been interrupted, a well-behaved thread would abandon what it is doing and end itself.
Assuming the above use-case, your code is likely to be interrupted if it is run within a Java framework or from some worker thread. And when it is interrupted, your code should abandon what it is doing and cause itself to end by the most appropriate means. Depending on how your code was called, this might be done by returning or by throwing some appropriate exception. But it probably should not call System.exit()
. (Your application does not necessarily know why it was interrupted, and it certainly does not know if there are other threads that need to be interrupted by the framework.)
On the other hand, if your code is not designed to run under the control of some framework, you could argue that the InterruptedException
is an unexpected exception; i.e. a bug. In that case, you should treat the exception as you would other bugs; e.g. wrap it in an unchecked exception, and catch and log it at the same point you deal with other unexpected unchecked exceptions. (Alternatively, your application could simply ignore the interrupt and continue doing what it was doing.)
1) If I'm never ever interrupting other threads myself, what can trigger an InterruptedException?
One example is if your Runnable
objects are executed using an ExecutorService
and shutdownNow()
is called on the service. And in theory, any 3rd-party thread pool or thread management framework could legitimately do something like this.
2) If I'm never ever interrupting other threads myself using interrupt() ... what does an
InterruptedException
then mean? What am I supposed to do upon catching one? Shutdown my app?
You need analyze the codebase to figure out what is making the interrupt()
calls and why. Once you have figured that out, you can work out what >>your<< part of the app needs to do.
Until you know why InterruptedException
is being thrown, I would advise treating it as a hard error; e.g. print a stacktrace to the log file and shut down the app. (Obviously, that's not always the right answer ... but the point is that this is "a bug", and it needs to be brought to the attention of the developer / maintainer.)
3) How do I find out who / what is calling
interrupt()
?
There is no good answer to this. The best I can suggest is to set a breakpoint on the Thread.interrupt()
and look at the call stack.
Related Topics
Sending Command to Java -Jar Using Stdin via /Proc/{Pid}/Fd/0
Why Does Java Rmi Keep Connecting to 127.0.1.1. When Ip Is 192.168.X.X
Java Installation Issues on Ubuntu
How to Resolve "Could Not Find Jni", Building Opencv on Raspberry Pi
Random Noclassdeffound Error in Web Application
Eclipse Swt Browser Crash (Linux 64Bit)
Create a File Using Runtime.Exec Using Echo in Linux
Hadoop Hdfs Showing Ls: '/Home/Hduser/Input/': No Such File or Directory Error
What Could Be Reason for "Prism-Es2 Error:Gl_Version (Major.Minor) = 1.4"
Can't Run Program with Processbuilder, Runs Fine from Command Line
Java Error When Trying to Run Netlogo Headlessly on a Cluster
Running a Scheduled Task Written in Java on a Linux Server
Invoking Bash from Java Interactively
Shuffle Multiple Files in Same Order
Using Xdg Directory Specification on Java Application
Java Version Still Showing as 1.4 Linux
How to Abort the Installation of an Rpm Package If Some Conditions Are Not Met in Specfile