Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Thread.sleep() with *interrupted status* set?

The Java documentation is not clear on this point. What happens if you call interrupt on a Thread before a call to Thread.sleep():

        //interrupt reaches Thread here
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            return;
        }

Will the InterruptedException be thrown?

Please point to relevant documentation.

like image 712
Roland Avatar asked Apr 14 '11 21:04

Roland


People also ask

Can thread sleep be interrupted?

A thread that is in the sleeping or waiting state can be interrupted with the help of the interrupt() method of Thread class.

What happens when thread's sleep () method is called?

Thread. sleep causes the current thread to suspend execution for a specified period. This is an efficient means of making processor time available to the other threads of an application or other applications that might be running on a computer system.

What happens when a thread is interrupted?

Threads can be interrupted, and when a thread is interrupted, it will throw InterruptedException. In the next sections, we'll see InterruptedException in detail and learn how to respond to it.


1 Answers

Yes, it will throw an exception. According to the javadoc for Thread.sleep, the method:

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

The 'has' in this case is an informal way of referring to the interrupted status. It's a shame that it is informal - if there's somewhere a spec should be precise and unambiguous, well, it's everywhere, but it's the threading primitives above all.

The way the interrupted status mechanism works in general is if that a thread receives an interruption while it's not interruptible (because it's running), then the interruption is essentially made to wait until the thread is interrupted, at which point it swoops in an causes an InterruptedException. This is an example of that mechanism.

like image 80
Tom Anderson Avatar answered Sep 28 '22 13:09

Tom Anderson