I've been trying to understand Reentrant locks and Semaphores ( the nesting of Reentrant locks vs release/unlock mechanism ).
It seems that having a Semaphore requires you to write a more thoroughly tested application because the release() method does not check if the thread releasing the permit is actually holding it. When I tested my test code, I found out that this subsequently increases the number of permits available. On the other hand, if a thread is not holding a reentrant lock when it invokes the unlock method, we get an IllegalMonitorException.
So would it be right to say that there is no real reason ever to have a binary semaphore as everything that a binary semaphore can do can also be done by a reentrant lock. If we use binary semaphores we would have to check the entire method call stack to see if a permit was acquired before ( also was it released too if there is a possibility of a subsequent acquire - which might block if a release does not proceed it and so on ). Also since reentrant locks also provide one lock per thread, isn't it always a better idea to prefer a reentrant lock to a binary semaphore?
Joined: Sep 06, 2012
I've posted this question in two other forums as well.
You are right. Usually you will use Reenterant lock (because you need a locking in a first place) and not a semaphore. Locks are used much often than semaphores (all semaphores, not only the binary ones).
There are some small differences between Semaphore and reenterant lock. Semaphore may be released by another thread. Semaphore's javadoc states that such behavior may be useful in some specialized contexts like deadlock recovery. I never found cases where binary semaphores are better that locks. So it should be a really specialized contexts. Also binary semaphores are not reenterant. You cannot acquire a binary semaphore second time in a same thread. It will lead to a deadlock (deadlocking thread with itself!) and you may need some means of already mentioned deadlock recovery
Wrong "releases" of a semaphore is not a big problem by itself. It is almost the same as wrong "releases" of the reentrant lock. And non-releasing a lock/semaphore proper number of times is much worse problem (these missed locks will be hard to spot). In most cases you should use locks in a structured manner:
If you are accustomed to this pattern, then it is very easy to spot missing or misplaced unlock call.