• Post Reply Bookmark Topic Watch Topic
  • New Topic

wait in while loop?

 
Vasim Patel
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Apologies for some basic questions.

1. Why is it necessary to put a wait() in a while loop. What happens if we don't.
Is it a good programming practise or is it a MUST for wait() to function properly?

2. Also, when is an InterrupedException thrown? Can you anyone give me me a code snippet in which an InterruptedException is throw?

regards
Vasim
 
Stephen Bloch
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In Joshua Bloch's Effective Java, chapter 50 is entitled "Never invoke wait outside a loop." To summarize, the availability condition must be checked both before the wait, to avoid waiting forever for a notification that will never come; and after the wait, to ensure safety: some other thread could have grabbed the resource between the wait and the use of the shared resource, or some other thread could have called notify or notifyAll when the resource wasn't really available.

Habibi et al's SCJD prep book puts it differently:
An if statement will resume exactly where it left off... If the value of [the while-condition] has been changed by another thread... in the meantime the if statement will not recheck it.... A while loop, on the other hand, will always recheck the condition before resuming thread execution.

[ December 06, 2004: Message edited by: Stephen Bloch ]
 
Mr. C Lamont Gilbert
Ranch Hand
Posts: 1170
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Vasim Patel:
Hi,

Apologies for some basic questions.

1. Why is it necessary to put a wait() in a while loop. What happens if we don't.
Is it a good programming practise or is it a MUST for wait() to function properly?

2. Also, when is an InterrupedException thrown? Can you anyone give me me a code snippet in which an InterruptedException is throw?

regards
Vasim



1. What are you waiting for? How do you know it has arrived? I would say its good practice. In fairness its to prevent other errors from messing up your waiting. If all things worked perfectly, you could program not to need it. Too many people use notifyAll() when they should just use notify().

2. But things dont work perfectly, and there have been rumors of suprious InterruptedExceptions being thrown. InterruptedExceptions are thrown generally when you call interrupt() on an object.
 
Maulin Vasavada
Ranch Hand
Posts: 1873
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi vasim,

I thought you are being responded about the same question at,
http://www.coderanch.com/t/326539/java/java/wait-while-loop

Regards
Maulin
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!