Was my object signalled or did the wait Timeout ?
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   zohar_melamed
Posted On:   Friday, May 25, 2001 04:47 AM

Hi This question concerns the : public final void wait(long timeout) form of wait. Is it not odd that it returns void , and gives no indication of whether it timed out , or the object was signaled ... Trying to implement a Semaphore I was thinking this : (some details ommited) public synchronized boolean acquire(long waitFor) { if(count == 0){ if(wait(waitFor) == timedOut){ retrun false; }else{ count--; return true; } } However since wait(timeout) is void There i   More>>

Hi


This question concerns the :
public final void wait(long timeout)

form of wait.


Is it not odd that it returns void , and gives no indication of whether it timed out , or the object was signaled ...


Trying to implement a Semaphore I was thinking this : (some details ommited)



public synchronized boolean acquire(long waitFor)

{

if(count == 0){

if(wait(waitFor) == timedOut){

retrun false;
}else{

count--;

return true;

}

}



However since wait(timeout) is void There is no way to find out if it timed out ...


I have solved this particular case , but was wondering about this problem in general


Cheers


Zohar

   <<Less

Re: Was my object signalled or did the wait Timeout ?

Posted By:   Christopher_Schultz  
Posted On:   Friday, May 25, 2001 07:10 AM

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 yuor 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
About | Sitemap | Contact