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.
Related
From multiple articles around the internet it's advised not to swallow InterruptedException. It makes much more sense to do it with thread pool executors something like this when I'm going to reuse the same thread.
public static void main(String[] args) throws InterruptedException {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<?> future = executor.submit(() -> {
printNumbers(); // first call
printNumbers(); // second call
});
Thread.sleep(3_000);
executor.shutdownNow(); // will interrupt the task
executor.awaitTermination(3, TimeUnit.SECONDS);
}
private static void printNumbers() {
for (int i = 0; i < 10; i++) {
System.out.print(i);
try {
Thread.sleep(1_000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // preserve interruption status
break;
}
}
}
Code sample above from DZone.
But in the case of creating new thread each time like:
Object LOCK = new Object();
public void doSomeJob() {
myThread = new Thread(new Runnable() {
public void run() {
try {
synchronized(LOCK) {
System.out.println("Inside run");
LOCK.wait();
}
} catch(InterruptedException ignored){}
}
}
}
Do I still need to call Thread.currentThread().interrupt();? Will that make any sense?
Good references:
https://codepumpkin.com/interrupt-interrupted-isinterrupted-java-multithreading/
http://michaelscharf.blogspot.com/2006/09/dont-swallow-interruptedexception-call.html
I will give an answer based on section 7.1.2 of great book Concurrency in Practice by Brian Goetz.
In your first example you use ExecutorService. ExecutorService manages it's own threads. You are not the owner of those Threads so you do not know what interruption means to them ( for example ThreadPool might choose to kill Threads that were interrupted and create new ones). That is why you should preserve interruption status when you submit a cancelable task to this pool. This citation applies to this case:
Tasks do not execute in threads they own.They borrow threads owned by a service such as a thread pool. Code that
doesn't own the thread (for a thread pool, any code outside of the thread pool implementation) should be careful to
preserve the interrupted status so that the owning code can eventually act on it, even if the "guest" code acts on the
interruption as well. (If you are housesitting for someone, you don't throw out the mail that comes while they're away - you save it and let them deal with it when they get back, even if you do read their magazines.)
In the second case you manage an instance of Thread manually. So you are the owner of it. Therfore you decide what interruption means to this Thread and you do not have to preserve the Interruption Status in the second case if you do not want to apply any Thread Interruption Policy for it :
What you should not do is swallow the InterruptedException by catching it and doing nothing in the catch block, unless your code is actually implementing the interruption policy for a thread
Note also that Thread Interruption Policy is different than Task Cancellation Policy :
Thread Interruption Policy - defines how Thread reacts to interruption (for example ThreadPool might kill Thread that was interrupted and create a new one). It is defined by the owner of the thread.
Task Cancellation Policy - defines how task reacts to cancellation. Cancellation is usually implemented with interruption. The one who implements the task chooses if task in responsive to interruption. This is easily achieved if your task calls methods that throw InterruptedException. Or you can check the interruption flag of the Thread by calling Thread::isInterrupted (for example in a loop). The implementor of the task chooses how to handle this.
Also you should not take any assumptions of Thread Interruption Policy (if you are not the owner of the Thread). That is why preserving Interruption Status or rethrowing InterruptedException is considered a good practice.
If your lock comes from java.util.concurrent.locks.Lock and is interruptible (using .lockInterruptibly()), it does make sense to interrupt the process so everything might be interrupted and cancelled.
Read chapter Implementation Considerations from the documentation.
But if your lock is non-interruptible (using .lock()) it will not make sense as you won't be able to interrupt the lock.
In your case, you're using wait() which is interruptable as written here, and will throw an InterruptedException.
The explanations in DZone link https://dzone.com/articles/understanding-thread-interruption-in-java in your question are very detailed. Thread.currentThread().interrupt(); raises back interrupted exception status which is cleared before by blocking methods (sleep). It is done to ensure second loop interrupted too (it will catch the exception as it is on the same thread).
Before I finish, I wanted to emphasize on an important detail about
what happens to a thread’s interruption status when a blocking code
responds to interruption by throwing InterruptedException. I had left
out the detail till now to avoid confusion.
Before a blocking code throws an InterruptedException, it marks the
interruption status as false. Thus, when handling of the
InterruptedException is done, you should also preserve the
interruption status by callingThread.currentThread().interrupt().
Let’s see how this information applies to the example below. In the
task that is submitted to the ExecutorService, the printNumbers()
method is called twice. When the task is interrupted by a call
toshutdownNow(), the first call to the method finishes early and then
the execution reaches the second call. The interruption is called by
the main thread only once. The interruption is communicated to the
second execution of the printNumber() method by the call to
Thread.currentThread().interrupt() during the first execution. Hence
the second execution also finishes early just after printing the first
number. Not preserving the interruption status would have caused the
second execution of the method to run fully for 9 seconds.
Where to use Thread.currentThread().interrupt(); depends on your code, second example is not complete to understand the need for it.
I am new to future and multithreading in java. I have a simple problem which has turned out to be complex, I have a number of threads (all have open sessions in them) which are open infinitely. Whenever one thread throws a custom exception (a timeout exception on the session), I have to interrupt all the threads and close all sessions gracefully. What I do is that I store the future objects returned by the threads (in an ArrayList) and loop through it and issue future.cancel for all when one thread throws an exception.
private static void futureCancel()
{
for(int i=0;i<numberStreams;i++)
{
Future<String> future=futureList.get(i);
try{
future.cancel(true);
future.get();
}
catch(InterruptedException e)
{
System.out.println("In interrupted block!");
} catch (ExecutionException e) {
e.printStackTrace();
}
}
return;
}
The issue here is that I cannot add InterruptedException in my thread code due to some requirement issues and the way things work on the other side of the sessions. If I throw an InterruptedException from my callable, it does not reach the catch block specified above. Incase I add sleep in my thread (ok for testing) and handle the InterruptedException, it enters that block as soon as future.cancel is issued. What am I doing wrong?
Futuer#cancel(boolean) javadoc states
This attempt will fail if the task has already completed, has already
been cancelled, or could not be cancelled for some other reason. If
successful, and this task has not started when cancel is called, this
task should never run. If the task has already started, then the
mayInterruptIfRunning parameter determines whether the thread
executing this task should be interrupted in an attempt to stop the
task.
So either the ExecutorService hasn't executed the Runnable/Callable and can remove it from its queue or it has and the ExecutorService has to call Thread#interrupt() and your Runnable/Callable code has to handle it.
There's no other way through the Future interface to interrupt a thread. If your Runnable doesn't have a way to handle interrupts, then a number of things can happen. If an InterruptedException occurs, it will bubble up to the ExecutorService and be wrapped in a ExecutionException that will be thrown from Future#get(). If no InterruptedException occurs in the thread executing the Runnable, your Runnable will continue unhindered.
You should really consider changing your Runnable to handle interrupts.
If I throw an InterruptedException from my callable, it does not reach the catch block specified above.
It won't. The InterruptedException catch block around the future.get() is when the thread that is calling the get gets interrupted -- not your Callable.
If your Callable is interrupted and throws InterruptedException then when you call get() it will enter the ExecutionException and the e.getCause() should be InterruptedException.
I have a thread which may get stuck and keep running forever. Thus after a certain amount of time, I would like it to stop executing, go to the finally method to do cleanup, and then die. How would I go about doing this safely? Thanks.
My first thought on how to do this was to make a child thread and have that sleep and then do the cleanup. But then when the parent thread is still trying to run and it can't so it outputs an error.
Refactor your code into a Callable and use an ExecutorService to get a Future. Then use get with a timeout, which throws a TimeoutException if not done by then. See https://stackoverflow.com/a/2275596/53897 for a full example.
You need to set timeouts for your blocking calls. If there are no timeouts, abstract the call and time it out that way.
You could create 1 thread the poll the task for its completion status, and kill it if its exceeded some value. The task itself would still require yet another thread. I'd do this by creating tasks which have a staleness value. Poll all tasks periodically, if they are stale, cancel them.
Suggestion 1: If you put your code in a try block with a wait() statement you can catch interruptedException which will then follow to your finally. Another thread will have to send a notify() or notifyAll() to cause the interruption whenever circumstances need to interrupt your thread.
Suggestion 2: I'm only just a beginner with Java but the thread getting stuck means you must be able to throw a custom exception inside your try/finally block.
(1)
Best solution is to send your data with a timeout. Should look something like
try {
mySendingDataLibraryApi.sendData(data, timeout /*, timeUnit */);
// some new APIs enable also to configure the time unit of the required timeout.
// Older APIs typically just use milliseconds.
} catch (TimeoutException e) {
doCleanup(); // your cleanup method.
}
(2)
If this isn't applicable since the API you're using doesn't expose such configuration, second best solution would be to use an interruptible API sendData method and interrupt the executing thread. This relies on the fact that such an interruptible API is provided. I wouldn't count much on the existence of such a method if a timed method isn't provided by the API... Anyway, the code in the thread that executes the task would look like:
class MySendingDataRunnable implements Runnable {
#Override
public void run() {
try {
mySendingDataLibraryApi.sendDataInterruptibly(data);
} catch (InterruptedException e) {
doCleanup(); // your cleanup method.
// here either re-throw InterruptedExecption
// or restore the interrupted state with Thread.currentThread().interrupt();
}
}
}
The code in the caller the thread, should use an ExecutorService and the Future instance returned by its Future<?> submit(Runnable task) method, in order to wait the desired time and cancel the task with the mayInterruptIfRunning argument set to true:
final ExecutorService executor = Executors.newSingleThreadExecutor();
final Future<?> future = executor.submit(new MySendingDataRunnable());
try {
final Object noResult = future.get(60, TimeUnit.SECONDS); // no result for Runnable
} catch (InterruptedException e) {
// here again either re-throw or restore interupted state
} catch (ExecutionException e) {
// some applicative exception has occurred and should be handled
} catch (TimeoutException e) {
future.cancel(true); // *** here you actually cancel the task after time is out
}
(3)
If the API you use provide neither of these features (timed / interruptible methods), you'll have to use your creativity! This one line of blocking code of yours must be blocking on some resource. Try to reach out for this resource and shut it down or disconnect from it, implicitly causing the task to terminate. A typical example is closing a network connection.
Note: the above solutions only provide a way of actually cancelling the task and freeing the thread for further tasks. The thread might still be alive though. Killing the thread is usually not something that you do when a task is completed (or failed for that matter). It is acceptable when you've created some thread(s) for specific task(s) which isn't supposed to be executed ever again. In such cases you use the above ExecutorService and invoke its shutdownNow() method. And even shutdownNow() only makes best effort and typically depends on the the actual task to be interruptible...
Here's a detailed article (somewhat old but nonetheless).
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.
I'm using java.util.concurrent.Semaphore in a hobby project. It's used in a connection pool class I'm writing. I can use it with little fuss, except for this method:
public void acquire(int permits) throws InterruptedException
which forces me to handle the InterruptedException. Now, I'm not sure what "interrupting" a Thread even means and I'm never doing it (well, not explicitly anyway) in my code. Does this mean I can ignore the exception? How should I handle it?
Yes, you need to worry about InterruptedException, just as you need to worry for any other checked exception which you must either throw or handle.
Most of the times an InterruptedException signals a stop request, most likely due to the fact that the thread which was running your code was interrupted.
In your particular situation of a connection pool awaiting to aquire a connection, I would say that this is a cancellation issue and you need to abort the aquisition, cleanup, and restore the interrupted flag (see below).
As an example, if you're using some sort of Runnable/Callable running inside an Executor then you need to handle the InterruptedException properly:
executor.execute(new Runnable() {
public void run() {
while (true) {
try {
Thread.sleep(1000);
} catch ( InterruptedException e) {
continue; //blah
}
pingRemoteServer();
}
}
});
This would mean that your task never obeys the interruption mechanism used by the executor and does not allow proper cancellation/shutdown.
Instead, the proper idiom is to restore the interrupted status and then stop execution:
executor.execute(new Runnable() {
public void run() {
while (true) {
try {
Thread.sleep(1000);
} catch ( InterruptedException e) {
Thread.currentThread().interrupt(); // restore interrupted status
break;
}
pingRemoteServer();
}
}
});
Useful resources:
Shutting down threads cleanly (Java Specialists)
Dealing with InterruptedException (Brian Goetz)
Nope. InterruptedException is only generated if you interrupt your thread yourself. If you do not yourself use Thread.interrupt() then I would either re-throw it as some sort of "unexpected exception" or log it as an error and move on. For instance in my code when I am forced to catch InterruptedException and I never call interrupt() myself, I do the equivalent of
catch (InterruptedException exception) {
throw new RuntimeException("Unexpected interrupt", exception);
}
That's if it is unexpected. There are plenty of places where I deliberately interrupt my threads and in those cases I handle the InterruptedExceptions in a well-defined way. Usually that's by exiting whatever loop I'm in, cleaning up, and then stopping the thread.
Threads can be interrupted by calling Thread.interrupt(). It is used for gracefully signalling a thread that it should do something else. Usually it causes blocking operations (e.g. Thread.sleep()) to return earlier and throw the InterruptedException. If the thread gets interrupted, a flag gets set on it. This flag can be queried via Thread.isInterrupted() call.
If you don't use thread interruption and still get this exception, you could just exit your thread (and preferrably log the exception).
In general, it depends on what your multi-threaded application does.
If you don't know how to handle it in a method I suggest you declare it in the method with throws InterruptedException (and it caller etc)
If it something you never expect to occur I would catch it and wrap it in an AssertionError.
You should exit the run() method after you've performed any cleanup required by your Thread.
HTH