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).
Related
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.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am able to understand Threads and interrupts. I was trying to map the underlying concepts learnt from Oracle tutorial to understand concept of interrupts better. I developed this example and tried hard to understand the output as how interrupts are playing a role here. I just did not understand. So my notion was to ask someone to help me understand the output of this program which will clear me more about underlying functionality of interrupts.
public class ThreadSleepTest {
public static void main(String[] args) throws InterruptedException {
MyRunnable myRunnable = new MyRunnable();
Thread one = new Thread(myRunnable);
one.setName("Fred");
Thread two = new Thread(myRunnable);
two.setName("Lucy");
Thread three = new Thread(myRunnable);
three.setName("Ricky");
one.start();
two.start();
three.start();
//Thread.sleep(1000);
one.interrupt();
}
}
class MyRunnable implements Runnable {
public void run() {
for (int x = 1; x < 4; x++) {
System.out.println("Run by: " + Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
System.out.println("Exception occured");
}
}
System.out.println("Do something");
}
}
Here is the output from my console.
Run by: Lucy
Run by: Fred
Run by: Ricky
Exception occured
Run by: Fred
Run by: Fred
Run by: Lucy
Run by: Ricky
Do something
Run by: Lucy
Run by: Ricky
Do something
Do something
Once a thread is interrupted, it is basically taken out of operation as per my understanding.
No, your understanding is incorrect. Once a thread is interrupted, it is up to the programmer who wrote the run method to decide what to do about it.
Thread termination is entirely up to the programmer, as the JVM doesn't actually know what resources and locks you may need to clear up when you terminate the thread. This is the reason why the methods stop() and suspend() in Thread have been deprecated. They are not safe.
So when a thread is interrupted, if you are in a method that throws an InterruptedException, you have to react to this exception and finish whatever it is you are doing, and if you are in the middle of your own stuff, you have to check the interrupted() status of the current thread from time to time, and if an interrupt occured, finish up what you are doing.
Here is what you chose to do when your thread is interrupted:
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
System.out.println("Exception occured");
}
In your catch clause, you are merely printing the fact that the exception occured. You are not actually doing anything towards termination of the thread. Therefore, it will not be terminated. You'll go out of the catch clause, and continue with the next iteration of your loop.
Thread.sleep() by convention clears the interrupted flag when it throws the InterruptedException. So in the next iteration, the thread is no longer "interrupted", and sleep() does not throw the exception again.
Interrupting a thread means signaling it to stop doing what it currently does.
Most I/O and locking operations will interrupt when the thread the run on is interrupted and an InterruptedException is raised in that thread (however, not all operations do so, for example see https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Semaphore.html#acquireUninterruptibly()).
The code is then able to process the exception in any way he/she sees fit. After the InterruptedException is raised, the interrupt signal is consumed, the thread can continue to do anything. In your example, the Thread.sleep() call finishes earlier, the InterruptedException is thrown and a message is logged. After that, the thread continues the for loop. Of course, the thread can be later interrupted.
I think the Java Concurrency in Practice (JCiP), page 138 gives a fairly good explanation of what might be happening. There are a few things that you can note:
The main thread creates and starts 3 threads named: Fred, Lucy, Ricky. Let's just consider the thread named Fred, which is assigned to the variable one (There are better ways of doing this e.g. the CountdownLatch).
Fred, after being scheduled to run is immediately put to sleep by your code. The method Thread.sleep is a well-designed blocking call. This means that it can be interrupted by sending an interrupt. This is exactly what main thread tries to do: request an interruption in whatever activity thread one is doing or not doing (since it's just sleeping in this case). The main thread does that by simply calling the interrupt() method on one. Note that this is perceived only as a 'friendly request' by the thread being interrupted.
In the case when you see the output 'Exception occurred', the (sleeping) interrupted thread acknowledges the interrupt and like it is documented, an InterruptedException is thrown. This exception is caught by one and the message 'Exception occurred' is printed on the stdout. Thus, the main thread has succeeded in interrupting what one was doing.
Other threads do their tasks without interruption (that's why you see the other print statements).
If you interrupt a thread, the next or current time you sleep or wait in this thread its going to throw an InterruptedException. BUT the interrupted state is cleared with this. If your Thread is interrupted, you should terminate it in the near future.
I am stopping the thread execution using Thread.interrupt but the thread execution won't stopped . It's still running .
Example :
Thread t = new Thread(new Runnable() {
#Override
public void run() {
int i = 0;
while(i<10000){
if(Thread.currentThread().isInterrupted()){
System.out.println("Thread Interrupted but it still running");
}
System.out.println(++i);
try {
Thread.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
t.start();
t.interrupt();
I can't check Thread.isInterrupted() then if thread is interrupted break out of the loop . I can't do this . Here , I am just showing the sample example .
My doubt is Thread.interrupt is only sets interrupted flag only or it really stops the execution .
any help regarding this will be appreciated.
How can I stop the thread execution or kill the running thread?
Thread.interrupt() will genuinely interrupt an operation that actually checks for that state (either, say, an interruptible I/O operation or else some user code that explicitly checks isInterrupted() as in principle you do in the code you quote).
In the specific example you quote, you need to bear in mind that:
each processor core executes in the order of billions of instructions
per second;
process switching occurs in the order of tens to hundreds
of times per second.
In other words, your task of decrementing a counter 10,000 times is something that happens so fast that to all intents and purposes it will barely register as being an "interruptible task". In practice, either all 10,000 decrements will happen before the other thread has chance to call interrupt() or they won't.
If the thread is blocked on wait, sleep or join then InterruptedException is thrown otherwise interrupted status is set.
Interrupted status is cleared if Thread.interrupted is called.
Thread.isInterrupted does not clear the interrupted status.
If the thread's interrupted status is set and this thread calls wait, sleep or join then interrupted status is cleared and InterruptedExcepion is thrown.
It only sets the flag UNLESS an interruptable statement (e.g. sleep, wait) was executing at the time. Now you should be able to work out how to stop the thread, by dealing with both situations.
I can't check Thread.isInterrupted() then if thread is interrupted
break out of the loop . I can't do this .
Why not?
E.g.
while(i<10000){
if(Thread.currentThread().isInterrupted()){
System.out.println("Thread Interrupted but it still running");
return; // HERE
}
System.out.println(++i);
try {
Thread.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
return; // HERE
}
}
My doubt is Thread.interrupt is only sets interrupted flag only or it really stops the execution.
It does the former ... or throws an "interrupted" exception in certain circumstances.
How can I stop the thread execution or kill the running thread?
In general, you cannot safely stop or kill a running thread that is not checking its interrupted flag. There are some deprecated methods on the Thread class, but you should avoid using them as they are manifestly unsafe. (To understand why the Thread method javadocs ... and the FAQ that it links to.)
For some reason I am confused over the following:
Assume that I have Thread A that absolutely needs to execute after Thread B has completed its processing.
A way to do this would be by Thread A joining Thread B.
Trivial example:
public class MainThread {
public static void main(String[] args){
Thread b = new Thread (new SomeRunnable(args[0]));
b.start();
try {
b.join();
} catch(InteruptedException e) {
}
// Go on with processing
}
}
My question is the following: What is the proper way to handle the exception in such a case?
In various example I have seen, even in text-books, the exception is ignored.
So if Thread A needs to be sure that Thread B is completely finished before proceding, if I end up in the catch due to an exception, can it be the case that Thread B may still actually be runnable/running? So what is the best way to handle this exception?
First of all you must understand what causes this exception to be thrown. Calling stop() on a thread is currently deprecated, instead when you want to stop a thread you are interrupting it by calling thread.interrupt(). This has no impact on a thread (!), the thread must explicitly check interrupted flag once in a while and stop processing gracefully.
However if the thread sleeps, waits on a lock or on another thread (by using join() like in your example) it cannot check this flag immediately or often enough. In these cases JVM will throw an exception from blocking method (let it be join()) signalling your thread that someone just tried interrupting it. Typically you can ignore that exception (meaning - do not log it) - it's the side effect that matters. For example breaking out of the loop:
public void run() {
try {
while(!isInterrupted()) {
Thread.sleep(1000);
//...
} catch(InterruptedException e) {
//no need to log it, although it's a good idea.
}
}
It's not a problem that you didn't log that exception - but you escaped from the loop, effectively terminating the thread.
Now back to your question. When your Thread A is interrupted it means some other thread requested terminating it, probably because the whole JVM shuts down or web application is being undeployed. In this case you shouldn't be doing anything except cleanup.
Moreover it most likely means Thread B is still running. But what JVM is trying to say is: "Danger! Danger! Stop waiting for whatever you were waiting for and run!".
What is the proper way to handle the exception in such a case?
Any time you get an InterruptedException the current thread should consider itself to be interrupted. Typically, that means that the thread should clean up after itself and exit. In your case, the main thread is being interrupted by another thread and should probably interrupt the Thread a that it started in turn, and then quit.
Although it is up to you whether the interrupt should be ignored I would suggest that it is a bad practice. If you were using the interrupt as some sort of signal to the thread then I would instead set some volatile boolean flag.
In terms of best practice when catching InterruptedException, typically I do:
try {
...
} catch(InterruptedException e){
// a good practice to re-enable the interrupt flag on the thread
Thread.currentThread().interrupt();
// in your case you probably should interrupt the Thread a in turn
a.interrupt();
// quit the thread
return;
}
Since catching the InterruptedException clears the interrupt flag for the thread, it is always a good idea to re-enable the interrupt flag in the catch block.
In various example I have seen, even in text-books, the exception is ignored.
Indeed. It is very bad practice to ignore any exception but it happens all of the time. Don't give into the dark forces!
can it be the case that Thread B may still actually be runnable/running?
Thread B can certainly still be running. It is the main thread that is calling the join() that has been interrupted.
When does Java's Thread.sleep throw InterruptedException? Is it safe to ignore it? I am not doing any multithreading. I just want to wait for a few seconds before retrying some operation.
You should generally NOT ignore the exception. Take a look at the following paper:
Don't swallow interrupts
Sometimes throwing InterruptedException is
not an option, such as when a task defined by Runnable calls an
interruptible method. In this case, you can't rethrow
InterruptedException, but you also do not want to do nothing. When a
blocking method detects interruption and throws InterruptedException,
it clears the interrupted status. If you catch InterruptedException
but cannot rethrow it, you should preserve evidence that the
interruption occurred so that code higher up on the call stack can
learn of the interruption and respond to it if it wants to. This task
is accomplished by calling interrupt() to "reinterrupt" the current
thread, as shown in Listing 3. At the very least, whenever you catch
InterruptedException and don't rethrow it, reinterrupt the current
thread before returning.
public class TaskRunner implements Runnable {
private BlockingQueue<Task> queue;
public TaskRunner(BlockingQueue<Task> queue) {
this.queue = queue;
}
public void run() {
try {
while (true) {
Task task = queue.take(10, TimeUnit.SECONDS);
task.execute();
}
}
catch (InterruptedException e) {
// Restore the interrupted status
Thread.currentThread().interrupt();
}
}
}
From Don't swallow interrupts
See the entire paper here:
http://www.ibm.com/developerworks/java/library/j-jtp05236/index.html?ca=drs-
If an InterruptedException is thrown it means that something wants to interrupt (usually terminate) that thread. This is triggered by a call to the threads interrupt() method. The wait method detects that and throws an InterruptedException so the catch code can handle the request for termination immediately and does not have to wait till the specified time is up.
If you use it in a single-threaded app (and also in some multi-threaded apps), that exception will never be triggered. Ignoring it by having an empty catch clause I would not recommend. The throwing of the InterruptedException clears the interrupted state of the thread, so if not handled properly that info gets lost. Therefore I would propose to run:
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
// code for stopping current task so thread stops
}
Which sets that state again. After that, finish execution. This would be correct behaviour, even tough never used.
What might be better is to add this:
} catch (InterruptedException e) {
throw new RuntimeException("Unexpected interrupt", e);
}
...statement to the catch block. That basically means that it must never happen. So if the code is re-used in an environment where it might happen it will complain about it.
The Java Specialists newsletter (which I can unreservedly recommend) had an interesting article on this, and how to handle the InterruptedException. It's well worth reading and digesting.
Methods like sleep() and wait() of class Thread might throw an InterruptedException. This will happen if some other thread wanted to interrupt the thread that is waiting or sleeping.
A solid and easy way to handle it in single threaded code would be to catch it and retrow it in a RuntimeException, to avoid the need to declare it for every method.
From the docs:
An InterruptedException is thrown when a thread is waiting,
sleeping, or otherwise occupied, and the thread is interrupted, either
before or during the activity.
In other words, InterruptedException occurs when some code has called the interrupt() method on a specific thread. It's a checked exception, and many blocking operations in Java can throw it.
The purpose of the interrupt system is to provide a alternative workflow for allowing threads to interrupt tasks in other threads. An interruption necessarily may not interrupt a running thread but it can also request that the thread interrupt itself at the next convenient opportunity.
Threads may get blocked for several reasons:
waiting to wake up from a Thread.sleep()
waiting to acquire a lock, waiting for I/O completion
waiting for the result of a computation in another thread, etc.
The InterruptedException is usually thrown by all blocking methods so that it can be handled and the corrective action can be performed.
However, in majority of the cases as our code is a part of a Runnable, in this situation, we must catch it and restore the status.
There are a handfull of methods in Java that throws InterruptedException. Some examples are:
Object class:
Thread.sleep()
Thread.join()
wait()
BlockingQueue:
put()
take()
From personal experience, I simply changed thread.sleep() into this.sleep()
The InterruptedException is usually thrown when a sleep is interrupted.