Is it ever a safe to always ignore InterruptedException calling Thread sleep() in Java

exception, java, multithreading

Solution

Here is a great article about this particular exception:

http://www.ibm.com/developerworks/java/library/j-jtp05236/index.html

Basically though, it shouldn't be ignored, the very least the code should do is propagate the interruption:

catch (InterruptedException e) { 
    // Restore the interrupted status
    Thread.currentThread().interrupt();
}

The author doesn't care that the sleep of his Thread is interrupted (which is a valid reason to swallow the exception); however the interruption might be required elsewhere in a Thread that the author didn't know or think about when he write his code:

whether or not you plan to act on the interrupt request, you still want to reinterrupt the current thread because a single interruption request may have multiple "recipients." The standard thread pool (ThreadPoolExecutor) worker thread implementation is responsive to interruption, so interrupting a task running in a thread pool may have the effect of both canceling the task and notifying the execution thread that the thread pool is shutting down.

Problem

While working on a project I came across this code intended for a production system: ``` public static void sleepUntil(long millisecondToWake) { while (true) { long currentMillisecond = System.currentTimeMillis(); if (currentMillisecond >= millisecondToWake) { break; } try { Thread.sleep(millisecondToWake - currentMillisecond); } catch (InterruptedException ignoredException) { // do nothing } } } ``` I've always stuck to the basic principle of never dropping exceptions as exposed by Joshua Bloch in Effective Java as well as supported with my own extensive experience having to debug code where someone else did drop an exception. To date, I have not found a case where it is a good idea (sometimes catching checked exception and throwing an runtime is debatably reasonable but I am not talking about those cases here). Thanks in advance for any comments.

Original source

Related problems