Win a copy of Spring in Action (5th edition) this week in the Spring forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Ganesh Patekar
  • Frits Walraven
  • Tim Moores
  • Ron McLeod
  • Carey Brown
Bartenders:
  • Stephan van Hulst
  • salvin francis
  • Tim Holloway

Thread methods  RSS feed

 
Ranch Hand
Posts: 186
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
object: wait, notify, notifyAll
Thread: sleep, yield, join

which ones have to be in a try block?
arent they meant to be?
i have seen too many codes and i have been confused if they are meant to.
 
Ranch Hand
Posts: 513
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's a simple trick for the exam: the only checked exception that any of these methods throw is InterruptedException. And, as the name implies, InterruptedException occurs if this thread is prematurely interrupted while it's supposed to be "inactive" in the background. Therefore, to figure out which of these six methods throw an unchecked exception, just ask yourself which of them will put the thread into an "inactive" state.

notify() and notifyAll() clearly do not, so they're out. yield() is a little trickier, but just remember that yield() is only a suggestion to the scheduler that it should temporarily go on to process another thread... but the scheduler can return to this thread at any time, so it's never premature to interrupt a yielded thread--thus yield() doesn't throw an InterruptedException either.

The other three methods (wait(), sleep(), and join()) all force the thread to become inactive until some condition is satisfied. Thus, if the thread is then interrupted before the condition is satisfied, this would be premature and will cause an InterruptedException.

And because InterruptedException is a checked exception, you must therefore always either handle or declare the exception in your calling method.
[ November 13, 2007: Message edited by: Kelvin Lim ]
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!