Thread.sleep() and InterruptedException

Hi

When doing Thread.sleep(), what is the point of InterruptedException? I cant see why its helpful at all.

Will this exception cancel my sleep? If all I want to do is to sleep my thread no matter what and after 10 seconds continue as usual, what should I code inside the caught exception? I am having trouble seeing the usage and how to deal with this exception that is required to catch.

I am really sorry if there is some obvious answer to this, but I am having a hard time dealing with this as I know nothing more than whats written in the API docs. Didn't find any answer by googling the subject either.

[634 byte] By [invictus2a] at [2007-10-3 8:09:31]
# 1
Yes, the InterruptedException will interrupt the sleep() call. It doesn't happen often, but you may see it if the JVM shuts down during the sleep() call. Quite often the catch block for the InterruptedException is empty.Brian
brian@cubik.caa at 2007-7-15 3:13:47 > top of Java-index,Core,Core APIs...
# 2
So it mean that the thread is stopped/canceled? Or can it continue afterwards?Do you have any example on usage of the catch block for this exception? Any situation where it would be wise to actually do anything there.
invictus2a at 2007-7-15 3:13:47 > top of Java-index,Core,Core APIs...
# 3

The Thread interrupt() mechanism is a cooperative cancellation mechanism that causes the interrupt bit of the thread to be set. A thread that is prepared to be "cancelled" can check the interrupt bit and respond accordingly. Because cancellation needs to be responsive when a thread might be blocking, some blocking library methods (eg sleep. wait(). join() and various blocking methods in java.util.concurrent classes) respond to the interrupt request by unblocking the thread and throwing the interruptedException - and clearing the interrupt bit in the process.

If you call one of these methods then you have to decide how to deal with the InterruptedException. The fact these methods block means that your method itself blocks. If it is part of an API used by others then you should (in general) indicate that it is a blocking method, and one that responds to cancellation requests, by declaring that your method throws InterruptedException. If this is a method that can't expose cancellation directly then you will have to catch the InterruptedException. If your code is part of a call chain, rather than always being at the top-level of a Thread, then when you catch InterruptedException you should always re-assert the interrupt so that your caller 9which may be responsive to interrupts/cancellation) knows that the interrupt occurred.

Having an empty catch block for an InterruptedException is not a good practice for any code called by other "client" methods.

I am not aware of any circumstance where threads will be interrupted during VM shutdown - unless your own application shutdown hooks do that.

davidholmesa at 2007-7-15 3:13:47 > top of Java-index,Core,Core APIs...