Semaphore | Java Concurrent API
Semaphore is the most common type of Synchronization Object which many of us familiar with. Semaphore use the counter mechanism to control access to the shared resources.
If the value of counter is greater than 0 ( > 0), then access to the resource is allowed.
Access is denied if the value is equal to zero ( = 0).
The count only counts when the access is permitted to the shared resource.
Thus, in-order for a thread to get access to the shared resource then the semaphore must grant the permission. So first, the thread tried to access the permission from the Semaphore.
How it works?
If suppose the value of semaphore is greater than zero, then the thread acquires the permit and so the value of semaphore gets decremented preventing another thread to get access. Else, the thread waits till the count of semaphore is incremented from zero to get the access.
Once the thread completes its process with the shared resource, it releases the permit and so the semaphore count will get incremented.
Generally, Semaphore has the following two Constructors
Semaphore(int num);
Semaphore(int num, boolean how);