Search code examples
javamultithreadinglockingsemaphorejava.util.concurrent

Semaphore of size 1 the best option?


If you have a resource that only once person should access at a time you could use a semaphore of size one or you could just use a single ReentrantLock instance?

What are the subtle difference that make one or the other the better decision?


Solution

  • There are differences:

    1. Semaphores can be acquired by one thread and released by another thread. This way, one thread can signal another thread. Semaphores with count 1 can also be used for mutual exclusion. Locks on the other hand are used only for mutual exclusion.
    2. Semaphores are not reentrant. This means a thread cannot acquire a semaphore when the permits are exhausted even if it has been acquired by the same thread. Locks can be reentrant.