Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Thread.sleep throw if the thread was already interrupted?

Given a thread which was interrupted while it was not blocked (i.e. no InterruptedException was thrown), does that thread throw an InterruptedException when it later attempts to sleep?

The documentation does not state this clearly:

InterruptedException - if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.

like image 807
mafu Avatar asked Oct 01 '22 19:10

mafu


1 Answers

Yes, it does.

The documentation perhaps isn't crystal clear on that point, but this is easy to both test (see the your own answer below, for example), and to see the canonical (HotSpot) implementation. Thread.sleep shells out to os:sleep which checks interruption before staring the sleep process as you can see here (look for os:sleep).

If this wasn't the case, interrupts would be more or less impossible to use. If they happened to arrive outside of any sleep() call they would be lost as subsequent sleep() calls would ignore them. You couldn't even re-interrupt the thread because it is already interrupted.

like image 52
BeeOnRope Avatar answered Oct 06 '22 18:10

BeeOnRope