java - Why should wait() always be called inside a loop -


I have read that we should always call a wait () from within a loop:

  while (! Condition) {obj.wait (); }  

It works well without a loop, why is it so?

You not only need a loop but check your position in the loop. Java does not guarantee that your thread will only be informed by informing () / informing () the call or the correct information () / notify (). Due to this property loop-less version can work on your development environment and may fail unexpectedly in the production environment. For example, you are waiting for something:

  synchronize (TheObjectYouAreWaitingOn) {while (! Carrien) {theObjectYouAreWaitingOn.wait (); }}  

Comes with a bad thread and:

  theObjectYouAreWaitingOn.notifyAll ();  

If the bad thread can not mess with carryOn then you are waiting for the right client.

Edit: Add some more samples. Waiting can be interrupted, it throws a blocked exposure, and you may have to try to wait-based depending on the needs of your business, you can leave the exception or wait for suppression.


Comments

Popular posts from this blog

c++ - Linux and clipboard -

What is expire header and how to achive them in ASP.NET and PHP? -

sql server - How can I determine which of my SQL 2005 statistics are unused? -