Week 145 — What is the Semaphore class and what is it used for?
Question of the Week #145
What is the Semaphore class and what is it used for?
5 Replies
A semaphore is a concurrency utility that can be configured with a given number of initially available permits.
The
acquire()
method can be used to wait for one permit to be available and reduce the number of permits by 1 once a permit is available.
On the other hand, the release()
method can be used to mark one permit as available. It is also possible to use the acquire
and release
methods in a way that acquires/releases multiple permits at once.
Semaphore
s can be used in scenarios where only a limited amount of threads should access a resource concurrently. They are typically used in try
-finally
blocks.
For example, the following code will create 10 threads trying to do some work using a semaphore that only allows 3 permits. This effectively limits it to 3 threads doing the work at the same time and the other threads need to wait until permits are available again.
When running the code above, one gets output similar to the following:
📖 Sample answer from dan1st
It's a package that manages access to a shared resource by controlling the number of threads that can access it concurrently. It implements the semaphore concept from computer science, which acts as a counter to regulate access to a resource pool
Submission from harshit_310
The
java.util.concurrent.Semaphore
class is a threading primitive that restricts access to a protected resource. It is similar to a synchronized
method or block, but is much more flexible. In the case of synchronized
, only a single thread can hold the monitor object's lock at any one time -- all other threads that might want to acquire the lock must wait until that first thread releases it. This can cause bottlenecks and deadlocks.
The Semphore
improves this situation by defining a structure that has a fixed number of available "permits". Resources that want to limit the number of active users of the resource -- such as a connection pool -- use a semaphore to ensure that users either receive an available resource or wait until one becomes available. It can also ensure that waiting users gain access to the resource in "request" order.
The number of available permits is set at construction time:
The resource manager then uses the semaphore in methods that acquire or release a resource:
By default, a Semaphore is "unfair" -- it will not make any guarantees about which waiting thread receives the next available resource. This has lower overhead and higher throughput, but could result in resource starvation for some threads. Semaphores that are managing access to a limited resource like a connection pool should generally be "fair". This is accomplished by passing a boolean parameter to the constructor:
⭐ Submission from dangerously_casual