Search code examples
javasynchronizationsemaphore

Is semaphore thread-safe when its permits variable bigger than 1?


Recently I have been studying the sleep barber, and I have comprehended that it seems like a binary semaphore when the permits value equals to 1. How about when it exceeds 1? Will one thread be exchanged by a new one without releasing when multiple threads acquired?

I think it is unsafe but I am not sure . It would be nice if you could tell me the difference between syncing and simultaneous access.


Solution

  • Semaphore works as a gate. It can't be qualified as thread-safe or thread-unsafe. Resources (in general objects) can be thread-safe or unsafe.

    If it is binary semaphore, only one thread can access your resources at any given moment. So there is no need to think about thread-safety.

    But if semaphore count is 2, two threads can simultaneously access the same resource. If your resource (some object) is thread-safe, you are good. Otherwise you would need to implement some kind of synchronization mechanism so that unsafe part can only be accessed by one thread at a time.