본문 바로가기
개발 공부 기록하기/- Kotlin & Java

Thread.sleep throw InterruptedException?

by soulduse 2016. 1. 7.
반응형

출처 http://stackoverflow.com/questions/1087475/when-does-javas-thread-sleep-throw-interruptedexception


종종 스레드를 종료하다 발쌩하는 예외인데 유용하다.



If you use it in a single threaded app (and also in some multi-threaded apps), that method 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 a:

} catch (InterruptedException e) {
  assert false;
}

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.

반응형