I can see how a "standard" Semaphore Class can be implemented in Java. However, I cant see how to implement a Binary Semaphore Class in Java. How does such implementation work? When should I call the wake and notify methods to wake and stop the threads that are on the semaphores? I understand what binary semaphores are, but I have no idea of how to code them.
Edit Note: Realize that I said "BINARY" Semaphore class. The standard Semaphore class I already did and I know its correct so the standard Semaphore Class does not interest me.
I would rather use the Lock class
Besides the naming matching, Java Semaphore is no way to implement a BinarySemaphore, and using Object wait/notify or synchronize is quite raw.
Instead, the Lock class provides almost the same locking semantics as a Semaphore with its lock/unlock (versus acquire/release by Semaphore), but it is specifically targeted to solve critical section functionality, where just one thread is expected to enter at once.
Worth noting Lock also provide try with timeout semantics thanks to tryLock method.
Here is a simple implementation I did for a binary semaphore:
This implementation has one property of binary semaphores that you cannot get with counting semaphores that only have one permit - multiple calls to release will still leave just one resource available. This property is mentioned here.
Here is straight from the Java site
I think, the whole reason of using higher-level abstracts such as Semaphore class is that you don't have to call low level
wait
/notify
.I think you're talking about mutex (or mutual exclusion locks). If so, you can use intrinsic locks. This kind of locks in Java act as mutexes, which means that at most one thread may own the lock:
Where lock is a mock object, used only for locking.
EDIT:
Here is an implementation for you — non-reentrant mutual exclusion lock class that uses the value zero to represent the unlocked state, and one to represent the locked state.
If you need to know where should you call
wait()
andnotify()
, have a look atsun.misc.Unsafe#park()
. It is used within java.util.concurrent.locks package (AbstractQueuedSynchronizer <- LockSupport <- Unsafe).Hope this helps.
You could have a look at the source code for the Java implementation of the Semaphore class (or perhaps use it directly?)
I have my own implementation of a Binary Semaphore in Java.
Tell me if you find any bug in the code please, but so far it always worked fine! :)