Could you explain what java.lang.Thread.interrupt() does when invoked?
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.
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
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.
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;
}
}
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.
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.
If thread is already sleeping and interrupt() is called, thread will come out of sleeping state and throw interrupted Exception.
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
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
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.
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
I want to add one or two things to the above answers.
One thing to remember is that, calling on the interrupt method does not always cause InterruptedException. So, the implementing code should periodically check for the interrupt status and take appropriate actions.
Thread.currentThread().isInterrupted() can also be used to check the interrupt status of a thread. Unlike the Thread.interrupted() method, it does not clear the interrupt status.
Related
If I use this method like this, will it interrupt the thread or not?
while ( !interrupted() && more work to do){ /* main thread execution loop*/ }
2nd question: what does this statement mean?
interrupt() method, does not automatically mean that the thread should
terminate. It simply grabs the attention of the thread (kind of like
poking a sleeping roommate to wake him up)
Calling interrupted() does not “interrupt” execution of code in the Thread. Your condition will, however, cause the loop to exit if the Thread running it is interrupted by another thread calling interrupt() on it, assuming no other code in the loop calls interrupted() (which clears the current Thread’s interrupted status).
The text you have quoted is explaining that a Thread’s code must act on an interrupt, by checking the Thread’s interrupted status, or by calling a method capable of throwing InterruptedException (or ClosedByInterruptException). If the Thread’s code does none of those things, calling interrupt() on that Thread will have no effect on code execution; it will merely set the Thread’s interrupted status, which is just a boolean property of the Thread. Code must properly respond to interrupts for interrupts to be effective.
The below wait() call is always throwing InterruptedException. It is not that some other thread is interrupting it. There is no delay between the call and the exception being thrown. I have put logs to check the time lapse between the call and the catch of exception.
Also, Thread.sleep(long) yields the same result.
public synchronized void retryConnection()
{
// . .. some code
try
{
wait();
}
catch(InterruptedException e)
{
log(Level.SEVERE, "InterruptedException " , e);
}
// . .. some code
}
I have tried these random things:
call this method in a new thread. Then it works fine. It is a waiting and notification mechanism also works.
put the same code again, that is, wait again after the exception is caught. Then it is properly waiting.
Observation: When the call is coming from a netty(server) thread, it fails but if it is coming from some other java thread, it works. So my question is: Is there any mechanism or thread state where wait() or Thread.sleep() is forbidden and throws an exception if they are invoked?
I have checked the interrupted flag and it is 'false' always.
InterruptedException is a perfectly normal event to occur when using Object.wait(), and thread.sleep() coupled with Object.notify(), and Object.notifyAll().
This is called Inter-thread Communication.
A thread which owns the object's monitor, can call Object.wait() - a call which causes this current thread to lose the ownership of the monitor and to wait / block until another thread owning said object's monitor will call Object.notify() or Object.notifyAll().
This means that active thread owning the lock awakes other thread(s) from waiting (or sleeping, or blocking) state. This originating thread has to also relinquish its grasp on objects lock, before the thread(s) that got notified can proceed.
The thread which is waiting on a lock receives the notification as InterruptedException. It then can proceed as by the time it has received the exception, it has been given the ownership of the lock.
Please see Java Thread lifecycle diagram to for more information.
So in your case:
Receiving InterruptedException is not a failure.
Netty trying to be performant, does not let threads wait too long, hence you keep getting the notifications.
When you run your threads, you don't call notify() or notifyAll() and the exception is never thrown
For both Object.wait() and Thread.sleep() you get the following (from javaDoc):
The interrupted status of the current thread is cleared when this exception is thrown.
Well, I am trying to understand why the following combination of Thread.currentThread.interrupt() and return is working fine, when I want to terminate a current thread.
Thread.currentThread.interrupt();
return;
I write a small program:
public class Interr implements Runnable {
#Override
public void run() {
for(int i= 0; i<10000;i++){
System.out.println(i);
if(i==500){
Thread.currentThread().interrupt();
return ;
}
}
}
public static void main(String args []){
Thread thread = new Thread(new Interr());
thread.run();
}
}
I know I can also use Thread.currentThread.stop() but it is an unsafe way to terminate a thread. So I tried to use the combination interupt() and return.
It works but I do not undestand why it works.
Any Explanation?
Edit: in the above example, I am the owner of a Thread. Assume, I am not the owner of a thread. Why This combination is working?
You don't need interrupt(). The return is enough to exit run() which will then cause the thread to stop, since it has no more work to do.
No need to call interrupt() from same thread.
interrupt method will be used to interrupt a thread from other thread.
as per java docs.
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.
So it will send interrupt signal to the thread which is in I/O block.
#Override
public void run() {
while (true) {
}
}
if a thread has implementation like that , it wont interrupt even after calling this method.
Actually in the code you posted the reason the thread stops is because you called return.
As per the documentation, calling Thread.interrupt() does nothing more than set a flag on the thread you're calling it on. The owner of the thread checks the flag and must find a way to stop what it is doing.
I am learning locking mechanism in java and found out some code which was given as a example in the LockSupport class in which the thread interrupting itself by calling interrupt() method. I am very confused that when a thread is already running then why it is interrupting itself.
I also want to clear all of you that I know what happen when the current thread is interrupted inside the catch block but I want to know what happen when running Thread interrupt itself.
code from LockSupport
sample code is here
class FIFOMutex {
private final AtomicBoolean locked = new AtomicBoolean(false);
private final Queue<Thread> waiters = new ConcurrentLinkedQueue<Thread>();
public void lock() {
boolean wasInterrupted = false;
Thread current = Thread.currentThread();
waiters.add(current);
// Block while not first in queue or cannot acquire lock
while (waiters.peek() != current || !locked.compareAndSet(false, true)) {
LockSupport.park(this);
if (Thread.interrupted()) // ignore interrupts while waiting
wasInterrupted = true;
}
waiters.remove();
if (wasInterrupted) // reassert interrupt status on exit
current.interrupt(); // Here it is interrupting the currentThread which
}
public void unlock() {
locked.set(false);
LockSupport.unpark(waiters.peek());
}
}
I want to know what happen when running Thread interrupt itself.
The interrupt flag is set to true nothing else. Nothing magically like triggering an exception or signalling the thread.
If you interrupt another thread which is blocked on a interruptable method, this would trigger that method to throw an InterruptedException.
When you call
Thread.interrupted()
this clears the flag and if you want set it again, you need to use interrupt() to set the flag to true so other code can detect that the thread was interrupted.
A simpler solution is to use Thread.currentThread().isInterrupted() which doesn't clear the flag.
This is because Thread.interrupted() not only checks that the interrupt flag is set on the current thread, it also clears it!
Therefore it is needed to re-enable it.
The better solution here is to use Thread.currentThread().isInterrupted(), whih does not clear the interrupt flag.
And yes, it is only this: a flag. You don't "signal" a thread, in essence. When you receive an interrupted exception, it is because the callee will have detected that the interruption flag was set and thrown this exception (or "bubbled it up" from below). It doesn't happen "automagically".
In other words: in Java, thread interruption is a cooperative process.
What happens is that Thread.interrupted() returns and clears the thread interrupted flag; the code just resets the flag at the end; essentially postponing thread interrupts for a while.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
When does Java's Thread.sleep throw InterruptedException?
I saw we have to catch InterruptedException in the Thread.Sleep method, why? I never saw this exception occured in the real time. Any clue?
This happens if thread#1 is sleeping, and another thread interrupts it. This is usually an attempt to stop thread#1. For example, thread#1 is sleeping while doing some long-running task (perhaps in background) and the user hits a cancel button.
The IterruptedExeption is thrown when a thread is waiting, sleeping, or otherwise occupied, and the thread is interrupted, either before or during the activity. Occasionally a method may wish to test whether the current thread has been interrupted, and if so, to immediately throw this exception. The following code can be used to achieve this effect:
if (Thread.interrupted()) // Clears interrupted status!
{
throw new InterruptedException();
}
Every thread has a Boolean property associated with it that represents its interrupted status. The interrupted status is initially false; when a thread is interrupted by some other thread through a call to Thread.interrupt(), one of two things happens. If that thread is executing a low-level interruptible blocking method like Thread.sleep(), Thread.join(), or Object.wait(), it unblocks and throws InterruptedException. Otherwise, interrupt() merely sets the thread's interruption status. Code running in the interrupted thread can later poll the interrupted status to see if it has been requested to stop what it is doing; the interrupted status can be read with Thread.isInterrupted() and can be read and cleared in a single operation with the poorly named Thread.interrupted(). See.
There is no way to simply stop a running thread in java (don't even consider using the deprecated method stop()). Stopping threads is cooperative in java. Calling Thread.interrupt() is a way to tell the thread to stop what it is doing. If the thread is in a blocking call, the blocking call will throw an InterruptedException, otherwise the interrupted flag of the thread will be set.
The problem is that blocking calls like sleep() and wait(), can take very long till the check can be done. Therefore they throw an InterruptedException. (However the isInterrupted is cleared when the InterruptedException is thrown.)