Binary Semaphore vs a ReentrantLock

☆樱花仙子☆ 提交于 2019-11-28 17:29:47

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 ReentrantLock

If all you need is reentrant mutual exclusion, then yes, there is no reason to use a binary semaphore over a ReentrantLock. If for any reason you need non-ownership-release semantics then obviously semaphore is your only choice.

Also since reentrant locks also provide one lock per object, isn't it always a better idea to prefer a reentrant lock to a binary semaphore?

It depends on the need. Like previously explained, if you need a simple mutex, then don't choose a semaphore. If more than one thread (but a limited number) can enter a critical section you can do this through either thread-confinement or a semaphore.

I have checked a post here that talks about difference between a binary semaphore and a mutex but is there a thing like a mutex in Java?

ReentrantLock and synchronized are examples of mutexes in Java.

I will not explain re-entrant locks since John has already given a good explanation above and its an example of mutex in java along with Synchronized keyword.

However, if for any reason, you would like to have a better control over the locking mechanism, Semaphore can become handy. This means, your code will have to remain in-charge of who called acquire() and who called release() since Semaphore by nature is blind to it, all it cares is permit becomes available.

Another approach of your own mutex implementation using java is LockSupport. It works a bit like Semaphore but has a timeout on the permit, using park() function and only supports one permit at a time unlike Semaphores which support multiple of them.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!