aspose file tools*
The moose likes Threads and Synchronization and the fly likes My Semaphore Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "My Semaphore" Watch "My Semaphore" New topic
Author

My Semaphore

Swerrgy Smith
Ranch Hand

Joined: Mar 26, 2010
Posts: 84
Hi all,

I have implemented a Semaphore below, it seems to work well. However if in the method acquire() I replace [while (count==0)] by [if (count==0)] then the Semaphore doesn't work well anymore.
For me, there is nothing different, because if count==0 then the current thread will sleep. When the thread is notified, it will continue to execute from the code after wait() (that means it will not check the condition count==0 again). If so, [while (count==0)] and [if (count==0)] are the same.

Is this true?


Thank you very much.

Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 3950
    
  17

Swerrgy Smith wrote:... When the thread is notified, it will continue to execute from the code after wait() (that means it will not check the condition count==0 again). If so, [while (count==0)] and [if (count==0)] are the same.

Is this true?
That would only be true if you could rely that your object would only be notified when the release() method was called. That is not the case - there is a chance (a real chance) of of what the API calls spurious notifications and interruptions. You need to handle that case, or you will get into trouble with a thread coming out of the wait() when there is no count available.


Steve
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: My Semaphore
 
Similar Threads
Concurrency Utilities
few questions ...
synchronized
Java Semaphore
invoking notify()