Semaphore | Java Concurrent API

Amar Balu
The Fresh Writes
Published in
6 min readFeb 8, 2023

--

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.

Image Source : https://javadeveloperzone.com/spring-boot/spring-boot-tutorial/

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);

--

--

Amar Balu
The Fresh Writes

I'm a front-end developer. I love React and Redux, Java, and Data Science. I write code for fun!. Join our publication : https://medium.com/thefreshwrites