Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8073439

(thread) Add Thread.sleepQuietly et al to make proper interrupt handling more convenient

XMLWordPrintable

    • Icon: Enhancement Enhancement
    • Resolution: Unresolved
    • Icon: P5 P5
    • None
    • None
    • core-libs

      The current Thread.sleep(ms) is declared to throw InterruptedException. This has resulted in numerous instances of poor coding practices where the InterruptedException is caught and ignored. If sleep() is called from within a method that itself isn't declared to throw InterruptedException (or a supertype) then the recommended approach is to catch InterruptedException, reassert the interrupt status bit on this thread, and continue. This is rarely done in code "in the wild." It's easy to find examples of code that mishandles this.

      This RFE proposes to introduce a method Thread.sleepQuietly(ms) and Thread.sleepQuietly(ms, ns). Possibly, an equivalent method would be added to java.util.concurrent.TimeUnit.

      The name "sleepQuietly" is not set in stone. Another name could be substituted if a better one is found.

      The methods would *not* be declared to throw InterruptedException. Instead, the behavior would be to catch InterruptedException, set the thread's interrupt status bit, and return. This would mean that the call would sleep for less time than was indicated -- but that's kind of the point of being interrupted.

      A variation would be to add sleepUninterruptibly(), which would sleep for the full amount of time despite being interrupted. The use cases for this are less clear, but it should be considered. (Guava has a sleepUninterruptibly family of methods.)

      A simple implementation of Thread.sleepQuietly() might look like this:

          public static void sleepQuietly(long ms) {
              try {
                  Thread.sleep(ms);
              } catch (InterruptedException ie) {
                  Thread.currentThread().interrupt();
              }
          }

      This is merely a convenience method, but given the number of times code gets this wrong, it's worth having it in the platform.

            smarks Stuart Marks
            smarks Stuart Marks
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated: