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 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.