InterruptedException not being thrown by Thread.sleep

Viewed 236

I have a thread sleeping for some time and doing some work continuously.

public void run() {
    while(true) {
        try {
            Thread.sleep(SOME_RANDOM_TIME);
        } catch (InterruptedException e) {
            return;
        }
        doSomeLabour();
    }
}

I have a bunch of these threads running on Executors. When I call shutdownNow on the executor, the threads are not getting terminated sometimes. All shutdownNow does is it just calls interrupt on all the running threads and doesn't accept any new threads.

So, basically, I'm just interrupting all the threads.

I understand, that when thread is not in sleep, and it's interrupted, nothing will happen in case of my code; however, shouldn't sleep(..) be throwing InterruptedException next time when the thread tries to sleep after done with the work because the interrupted flag is still set on that thread?

1 Answers

How about

while(!Thread.currentThread().isInterrupted()) {
    try {
        Thread.sleep(SOME_RANDOM_TIME);
    } catch (InterruptedException e) {
        return;
    }
    doSomeLabour();
}

instead?

JDK Javadoc states for Thread.interrupt():

If this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.

So sleep() itself doesn't throw an InterruptedException, rather the interrupter does if the thread is currently sleeping.

Related