why need to catch InterruptedException in the Sleep? [duplicate] - java

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.)

Related

method interrupted in java,when use it inside while loop will interrupt the thread or not?

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.

wait() is always throwing InterruptedException

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.

Interrupting a blocking method before the method call

I'm reading this book, (O'Reillys Java Threads 3rd ed., which for now has very bad explanations), and I have encountered this code:
//in RandomCharacterGenerator class
public void run( ) {
while (!isInterrupted()) {
nextCharacter( );
try {
Thread.sleep(getPauseTime( ));
} catch (InterruptedException ie) {
return;
}
}
}
And the following explanation (producer is the instance of upper class in the main thread):
producer.interrupt( );
If the main thread executes this statement while the RandomCharacterGenerator thread is sleeping, the RandomCharacterGenerator thread gets the interrupted exception and immediately returns from the run() method. Otherwise, when the character-feeding thread next gets to the top of its loop, it sees that the interrupted flag has been set and returns from its run() method then. Either way, the random character generator thread completes its task.
Note that this technique does not completely eliminate the possibility that we sleep for some amount of time after the thread is asked to stop. It's possible for the main thread to call the interrupt() method just after the RandomCharacterGenerator has called the isInterrupted() method. The character-reading thread still executes the sleep() method, which won't be interrupted (since the main thread has already completed the interrupt() method). This is another example of a race condition that we solve in the next chapter. Since the race condition in this case is benign (it just means we sleep one more time than we'd like), this is sufficient for our purposes.
Second paragraph is completely unclear to me. My first question is: How can we sleep one more cycle? If we interrupt the thread when sleeping it goes out of run, if we interrupt before sleep it will interrupt sleep as soon as it starts sleeping (I tested that, and I think that's true? Am I right), if we interrupt after sleep it will brake the loop.
Second question: In this example (this is the whole code from the book) is the check in loop completely unnecessary, and can it stand while (true) with the same outcome, so that first paragraph about the top of the loop is complete nonsense?
The book is wrong. Interrupting the thread before it sleeps will make the sleep() method throw an InterruptedException immediately.
Quote from Java Concurrency in Practice:
A good way to think about interruption is that it does not actually interrupt a running thread; it just requests that the thread interrupt itself at the next convenient opportunity. (These opportunities are called cancellation points.) Some methods, such as wait, sleep, and join, take such requests seriously, throwing an exception when they receive an interrupt request or encounter an already set interrupt status upon entry.
(emphasis mine)
In this particular example, using while(true) would lead to the same effect. But in other cases, if the loop never calls an interruptible method, or if you want to exit as soon as possible, you'll have to regularly check if the thread is interrupted to be able to detect the interruption.
The book believes you will spend an extra cycle in the following case:
RandomCharacterGenerator -> isInterrupted = false;
Main -> interrupt()
RandomCharacterGenerator -> runs through code
RandomCharacterGenerator -> sleeps
RandomCharacterGenerator -> isInterrupted = true
It actually will interrupt on the sleep, but the thing it is trying to get at that is important is that you may run through the code one more time after calling interrupt()

Java InterruptedException - I'm confused as to what it even means for a thread to be interrupted or why it would be

I keep getting this exception inside of a synchronized block, in which I call wait on the same object I'm synchronized on. What does it mean for a thread to be interrupted first of all?
secondly, what are normal scenarios where this would happen? any advice as to what could be going on or what I should do?
The interrupt mechanism is used to inform a thread that it should terminate itself as soon as possible. This allows the interrupted thread to exit safely without leaving any data in an inconsistent state.
What does it mean for a thread to be interrupted first of all?
It means that something has called Thread.interrupt() on the thread object. This sets the interrupted flag on the thread, and causes certain method calls to terminate with an exception.
Secondly, what are normal scenarios where this would happen?
It is typically used when a second thread wants to tell this thread to stop what it is doing. The call could be direct, or it could be done by a library method. For instance, ThreadPoolExecutor.shutdownNow() uses interrupts to (try to) terminate executing tasks.
Note that interrupting a thread does not guarantee to stop it. Indeed, barring the cases where an exception is thrown, the thread will only notice that it has been interrupted if it calls interupted() or isInterupted(). Even then, it could simply clear the flag and continue as if nothing has happened.
Any advice as to what could be going on or what I should do?
Take a look at what is "controlling" the thread that got interrupted.

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

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.

Categories