• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Kaydell Leavitt
Ranch Hand
Posts: 689
Eclipse IDE Firefox Browser Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Pie
Posts: 20979
31
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Go back to the API documentation and read what the interrupt() method does.
 
Kaydell Leavitt
Ranch Hand
Posts: 689
Eclipse IDE Firefox Browser Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1638
IntelliJ IDE Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Sean Doherty
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic