I thought that the currently executing Thread will be stooped if the exception is thrown. Bu when I was going throught a java test a came across with the question:
Under which conditions will a currently executing thread stop?
When an interrupted exception occurs.
When a thread of higher priority is ready (becomes runnable).
When the thread creates a new thread.
When the stop() method is called.
A. 1 and 3
B. 2 and 4
C. 1 and 4
D. 2 and 3
The right answer was B, but what then happens if the exception is thrown? I thought the thread is terminating.
The right answer was B
No it wasn't. None of the answers given is correct.
but what then happens if the exception is thrown? I thought the thread is terminating.
No. The thread catches InterruptedException from whatever method it was calling that can throw it, for example Thread.sleep(). If it doesn't call such a method, nothing happens at all.
When a method throws InterruptedException, it is telling that it is a blocking method and that it will make an attempt to unblock and return early -- if you ask nicely.
When you try to interrupt a thread by calling interrupt() on the thread instance, it merely sends a signal. It depends on the actual thread to respond to that signal. Methods like Thread.sleep() and Object.wait() can look for this signal and make an attempt to stop what it is doing and return early and indicate its early return by throwing InterruptedException. So it's usually an acknowledgement from some blocking methods to the interrupt() request sent by some other thread.
Thread t = new Thread(() -> {
try {
Thread.sleep(5000); // Thread.sleep() allows a cancellation mechanism
} catch (Exception e) {
System.out.println("interrupted by some one else from outside");
}
});
t.start();
try {
t.interrupt();
t.join(); // waiting for the thread to finish its execution
System.out.println("back in main");
} catch (InterruptedException e) {
System.out.println("interrupted");
}
Output :
interrupted by some one else from outside
back in main
But if you have thread like this
Thread t = new Thread(() -> {
try {
for(int i=0;i<1_000_000;i++){
System.out.println(i);
}
} catch (Exception e) {
System.out.println("interrupted by some one else from outside");
}
});
Calling interrupt() on above thread will not do anything useful because we're not looking for the signal, so thread will print all numbers and join the main thread as if nobody ever asked it to stop doing what it is doing.
In case you want to learn more about this InterruptedException, I highly recommend thisBrian Goetz's article from IBM Developer Works
A thread, t, will stop if some other thread calls t.stop(), but please don't ever do that! One thread should never force another thread to do anything. Threads should always cooperate. Any program that calls t.stop() is very likely to contain bugs that you won't be able to fix without getting rid of the stop() call.
A thread will terminate (which is a kind of stop, right?) if some external process kills the JVM.
A daemon thread will terminate if the JVM shuts down because there are no non-daemon threads left to keep it alive.
A thread may stop or terminate because of the action of an attached debugger.
The only other reason why a thread will stop (and terminate) is if its run() method completes. A method can either complete normally by returning, or it can terminate abnormally (i.e., an exception is thrown and not caught within the method call.) A thread will terminate if its run() method completes in either way.
An InterruptedException doesn't affect a thread any differently from any other exception. If the thread catches the exception, then the thread will continue to run, but if no method in the thread catches it, then the thread's run() method will abnormally complete, and the thread will terminate (stop).
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.)
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.
I've had a test, and there was a question I lost some points on, because I wasn't able to answer it :
Which of the following is NOT a condition which can cause a thread to block :
Calling an objects's wait() method
Waiting for an I/O operation
Calling sleep()
Calling yield()
Calling join()
As far as I know, all of these are blocking calls :
wait() returns when an something calls notify(), blocks until then
If the thread is WAITING for an I/O operation then it's obviously blocked
sleep(), obviously, blocks until the time runs out, or something wakes up the thread
yield() "cancels the rest of the thread's timeslice" (lacking a better term), and returns only when the thread is active again
join() blocks until the thread it's waiting for terminates.
Am I missing something here?
yield(). it does not block the thread, what I mean it does not not put the thread in the BLOCK state, but it put the thread in the state READY - so it is available to the scheduler choose it again to execute. try to thing about the states of a thread. all operations but yield put the thread in the BLOCK state.
Also, calling join() on a thread that has already finished will NOT block. And sleep(0) will behave like yield() if there are no other threads that are eligible for execution.
What exactly happens when there is nothing on the queue and a take() is called. The API says the method will wait but does that mean the CPU spins checking for empty/not empty until an item is on the queue or does it mean that the thread yields and will be awoken by an interrupt? If it is the case of the former, I would probably want to see if the queue is empty and if it is call thread.yield() to give up processor time. My question is really do I need to call yield or does some inner mechanism handle that for me?
Secondly, what is the interrupted exception meant for? If I understand correctly it means that if thread A is executing this method and is waiting for input and another thread B calls threadA.interrupt() then thread A will catch the interrupted exception and presumably pause execution, if it is nice. Is that the correct way of thinking about it?
Note that BlockingQueue is an interface. So what follows is implementation dependent. If you look at the source code for (say) LinkedBlockingQueue, the source for take() calls lockInterruptibly() on a RentrantLock. From the doc for this:
If the lock is not available then the
current thread becomes disabled for
thread scheduling purposes and lies
dormant until one of two things
happens:
* The lock is acquired by the current thread; or
* Some other thread interrupts the current thread, and interruption of
lock acquisition is supported.
I suspect there's be some wait()/notify() or similar going on. Will it spin the CPU ? No (check via top or similar)
Re. your question on interrupts, the Java Specialist newsletter had a very interesting article on interrupt() and catching/handling the InterruptedException.
Read the article, but essentially if you catch the exception, you reinterrupt:
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt(); // very important
break;
}
The wait() call does not spin, it typically uses OS services to wait for an event/condition - which puts the thread to sleep until the condition/event is signaled again. No processor time is used while waiting.
You typically get the interrupted exception if the thread is blocking in a wait() call, and another thread calls interrupt() on that blocking thread, just like you said.
It is considered a bad practice to call yield() as it cannot ensure niceness - you may call it and the scheduler instantly returns to your thread as it were a no-op. Use timed waits (e.g. wait(1000)) instead.
Interruptions are a safe way to signal a thread that you want something from it - stop processing, wake up and respond to something, etc.
In general, these things depend on your concrete scenarios. Java has some nice features about concurrency which can be more applicable to a situation.