When does Java's Thread.sleep throw InterruptedException?

后端 未结 6 807
青春惊慌失措
青春惊慌失措 2020-11-27 13:32

When does Java\'s Thread.sleep throw InterruptedException? Is it safe to ignore it? I am not doing any multithreading. I just want to wait for a few seconds before retryi

6条回答
  •  时光说笑
    2020-11-27 13:34

    If an InterruptedException is thrown it means that something wants to interrupt (usually terminate) that thread. This is triggered by a call to the threads interrupt() method. The wait method detects that and throws an InterruptedException so the catch code can handle the request for termination immediately and does not have to wait till the specified time is up.

    If you use it in a single-threaded app (and also in some multi-threaded apps), that exception will never be triggered. Ignoring it by having an empty catch clause I would not recommend. The throwing of the InterruptedException clears the interrupted state of the thread, so if not handled properly that info gets lost. Therefore I would propose to run:

    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
      // code for stopping current task so thread stops
    }
    

    Which sets that state again. After that, finish execution. This would be correct behaviour, even tough never used.

    What might be better is to add this:

    } catch (InterruptedException e) {
      throw new RuntimeException("Unexpected interrupt", e);
    }
    

    ...statement to the catch block. That basically means that it must never happen. So if the code is re-used in an environment where it might happen it will complain about it.

提交回复
热议问题