[concurrency-interest] binary semaphore

Jeremy Manson jmanson at cs.purdue.edu
Mon Sep 19 11:13:27 EDT 2005

Michele Mazzucco wrote:

> How can I implement a binary semaphore in a bounded buffer environment, 
> say of capacity of one element (the binary semaphore has the property  - 
> unlike many Lock implementations - that the "lock" can be released by a 
> thread other than the owner), without using synchronized methods and 
> wait() and notify()/notifyAll() calls?

A Semaphore can basically keeps a count on how many items are in the 
bounded buffer.  You initialize the Semaphore with a number of permits 
equal to the bound.  Then, every time you call an add method, you 
acquire a permit, which blocks until a permit is available.  Once all of 
the permits are acquired, you have hit the bound on your buffer, and any 
further adds will block.  Similarly, every time you do a remove, you 
release a permit.

It looks more-or-less like this:

Semaphore s;

public MyBuffer() {
   s = new Semaphore(1); // or whatever your bound is

public void add(Object o) {
   // add object to collection

public Object remove(Object o) {
   // remove object from collection

Note that to do this correctly, access to the collection object still 
needs to be synchronized.  That can be hidden, though, if you use a 
synchronized wrapper class.


More information about the Concurrency-interest mailing list