When returning from a wait(long), can I tell whether my object was signaled or the wait timed out?

Christopher Schultz

There is a pretty standard way to check for this type of thing. You'll have to re-check your condition after the call to wait(timeout) returns:

public synchronized boolean acquire(long waitfor){
 if(count == 0){
  wait(waitfor);
 
 if(count == 0)
   return false;
    count--;
 }
  return(true);
}

Most developers usually put the wait(timeout) in a while loop, since your thread could be woken up by a notifyAll(), and another thread might have beaten you to the synchronization lock. In that case, you'll want to start waiting, again.

You should check out Doug Lea's Concurrent Programming in Java. It has lots of examples of guarded semaphores and locks and other stuff, all set in threaded environments.

Good luck,
-chris
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact