In Java, Thread.sleep() throws InterruptedException. What is the proper thing to do with this exception?
Should I
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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With