When does Java's Thread.sleep throw InterruptedException?

JavaMultithreadingSleepInterrupted ExceptionInterruption

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

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 queue; >
> public TaskRunner(BlockingQueue 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-

Solution 2 - Java

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.

Solution 3 - Java

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.

Solution 4 - Java

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.

Solution 5 - Java

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.

Solution 6 - Java

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

Solution 7 - Java

From personal experience, I simply changed thread.sleep() into this.sleep()

Solution 8 - Java

The InterruptedException is usually thrown when a sleep is interrupted.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMankiView Question on Stackoverflow
Solution 1 - JavaBrandon E TaylorView Answer on Stackoverflow
Solution 2 - JavaChristianView Answer on Stackoverflow
Solution 3 - JavaBrian AgnewView Answer on Stackoverflow
Solution 4 - JavaAnshikaView Answer on Stackoverflow
Solution 5 - JavastarblueView Answer on Stackoverflow
Solution 6 - Javaundetected SeleniumView Answer on Stackoverflow
Solution 7 - JavaYuviView Answer on Stackoverflow
Solution 8 - JavaBrutalOstView Answer on Stackoverflow