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

interrupted-exception, java, multithreading, sleep

Solution

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.

Problem

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.

Original source