Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

InterruptedException from Thread.sleep()

In Java, Thread.sleep() throws InterruptedException. What is the proper thing to do with this exception?

Should I

  1. propagate the exception up the call chain ?
  2. swallow the exception?
  3. be doing something else (please suggest)?
like image 832
Michael McCray Avatar asked Aug 02 '10 17:08

Michael McCray


People also ask

Why sleep method throws InterruptedException?

sleep() functions to execute, it always pauses the current thread execution. If any other thread interrupts when the thread is sleeping, then InterruptedException will be thrown.

What causes InterruptedException?

Class InterruptedException. 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.

Why InterruptedException should not be ignored?

InterruptedExceptions should never be ignored in the code, and simply logging the exception counts in this case as "ignoring". The throwing of the InterruptedException clears the interrupted state of the Thread, so if the exception is not handled properly the information that the thread was interrupted will be lost.

Who throws InterruptedException?

According to the JVM spec, InterruptedException may be thrown randomly by the JVM for no reason at all (known as a "spurious wakeups") Many threads may be waiting on the same condition, all may be woken (eg by notifyAll() ), but only one may advance when interrupted.


2 Answers

If all you're trying to do is burn SOME time, I would suggest just catching and ignoring the exception.

If, on the other hand, you need the proper amount of waiting time and any preemptive interruption is REALLY BAD for your program, then you should definitely rethrow the exception.

It just depends on why the exception occurred and what your use case is for Thread.sleep() in the first place.

like image 54
Platinum Azure Avatar answered Dec 01 '22 00:12

Platinum Azure


You should rethrow the exception.

This is an abstract from Brian Goetz, the author of the excellent book "Java Concurrency in Practice":

Dealing with InterruptedException:

If throwing InterruptedException means that a method is a blocking method, then calling a blocking method means that your method is a blocking method too, and you should have a strategy for dealing with InterruptedException. Often the easiest strategy is to throw InterruptedException yourself, as shown in the putTask() and getTask() methods in Listing 1. Doing so makes your method responsive to interruption as well and often requires nothing more than adding InterruptedException to your throws clause.

See : Dealing with InterruptedException

like image 23
Thierry-Dimitri Roy Avatar answered Dec 01 '22 01:12

Thierry-Dimitri Roy