aspose file tools*
The moose likes Threads and Synchronization and the fly likes Why does the method Thread.sleep() declare that it might throw an exception? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Why does the method Thread.sleep() declare that it might throw an exception?" Watch "Why does the method Thread.sleep() declare that it might throw an exception?" New topic
Author

Why does the method Thread.sleep() declare that it might throw an exception?

Kaydell Leavitt
Ranch Hand

Joined: Nov 18, 2006
Posts: 689

I don't understand why the method: Thread.sleep() might ever throw an exception. Should I put my call to sleep() within a loop, or would that defeat some purpose?



Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18669
    
    8

Go back to the API documentation and read what the interrupt() method does.
Kaydell Leavitt
Ranch Hand

Joined: Nov 18, 2006
Posts: 689

OK. I found the JavaDoc for the interrupt() method. I'll have to study this. Does anybody else have any ideas to help me understand this?

JavaDoc for the interrupt() method

Nitesh Kant
Bartender

Joined: Feb 25, 2007
Posts: 1638

Kaydell Leavitt wrote:OK. I found the JavaDoc for the interrupt() method. I'll have to study this. Does anybody else have any ideas to help me understand this?

JavaDoc for the interrupt() method



Interrupt is to indicate a thread that it should stop doing what it is currently doing and exit.
Sleep honors interrupt and since it is an exception condition, it indicates it by throwing an exception i.e. InterruptedException.
Whenever an interrupted exception occurs, you must always set the interrupted status back to the thread (via Thread's interrupt() method), stop what you were doing and return. So, the answer to your initial question that you should put sleep in a loop is "No". You should not eat InterruptedException unless you are pretty sure of it.


apigee, a better way to API!
Sean Doherty
Greenhorn

Joined: Apr 29, 2009
Posts: 13
Thread.sleep(millis) does not guarantee that it will sleep for the provided duration. No assumption can be made that if you specify it to sleep for 2seconds, its gonna sleep for 2 seconds. If there are any interrupts, then sleep can be interrupted, hence it throws an InterruptedException.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Why does the method Thread.sleep() declare that it might throw an exception?