binary semaphore

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

binary semaphore

Michele Mazzucco-2
Java APIs say "A semaphore initialized to one, and which is used such
that it only has at most one permit available, can serve as a mutual
exclusion lock" (binary semaphore)
(http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/Semaphore.html)

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?
_______________________________________________
Concurrency-interest mailing list
[hidden email]
http://altair.cs.oswego.edu/mailman/listinfo/concurrency-interest
Reply | Threaded
Open this post in threaded view
|

Re: binary semaphore

Jeremy Manson
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) {
   s.acquire();
   // add object to collection
}

public Object remove(Object o) {
   // remove object from collection
   s.release();
}

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.

                                        Jeremy
_______________________________________________
Concurrency-interest mailing list
[hidden email]
http://altair.cs.oswego.edu/mailman/listinfo/concurrency-interest