Is it always safe to always ignore the InterruptedException that throws Thread sleep () in Java

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 have always adhered to the fundamental principle: never throw exceptions that Joshua Bloch revealed in Effective Java, as well as being supported by my own extensive experience, which should debug code when someone else removed the exception. To date, I have not found a case where this is a good idea (sometimes catching a checked exception and throwing execution time is reasonably reasonable, but I'm not talking about these cases here).

Thanks in advance for any comments.

+6
source share
2 answers

Here is a great article about this particular exception:

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

In principle, it cannot be ignored, at least the code should propagate an interrupt:

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

It doesn’t matter to the author that the sleep of his flow is interrupted (which is a good reason for swallowing an exception); however, interruption may be required elsewhere on the thread, which the author did not know about and did not think when he wrote his code:

regardless of whether you plan to act in an interrupt request, you still want to translate the current thread, because a single interrupt request can have multiple "receivers". The implementation of the workflow of standard threads (ThreadPoolExecutor) responds to interruption, so the interruption of a task running in the thread pool can have the effect of both canceling the task and notifying the thread of thread that the thread pool is disabled.

+4
source

In this particular example, this does not seem reasonable. In particular, if the user wants to exit the program (for example), the JVM will freeze until your sleeping method ends, which seems unreasonable.

IMO, the only situation in which you can safely ignore InterruptedException is where:

  • you have full control over the thread executing your method, and
  • you exit immediately after ignoring the exception.

In any other situation, you must: reset the aborted flag and exit quickly.

For example, this will be fine:

 //the task is local, nobody else can access it final Runnable localRunnable = new Runnable() { public void run() { //catch, ignore and exit immediately try { Thread.sleep(10000); } catch (InterruptedException e) {} } } //it is your own thread and you have full control over it new Thread(localRunnable).start(); 
+3
source

Source: https://habr.com/ru/post/950174/


All Articles