In this example, we will show you how to make use of the Semaphore –
java.util.concurrent.Semaphore Class in Java.
1. What is a SEMAPHORE?
semaphore in Computer Science is analogous to a Guard at the entrance of a building. However, this guard takes into account the number of people already entered the building. At any given time, there can be only a fixed amount of people inside the building. When a person leaves the building, the guard allows a new person to enter the building. In the computer science realm, this sort of guard is called a
Semaphore. The concept of Semaphore was invented by Edsger Dijkstra in 1965.
The semaphores in computer science can be broadly classified as :
- Binary Semaphore
- Counting Semaphore
Binary Semaphore has only two states on and off(lock/unlock).(can be implemented in Java by initializing Semaphore to size 1.)
java.util.concurrent.Semaphore Class implements a counting
2. Features of Semaphore Class in Java
SemaphoreClass constructor takes a
intparameter, which represents the number of virtual permits the corresponding semaphore object will allow.
- The semaphore has two main methods that are used to acquire() and release() locks.
- The Semaphore Class also supports Fairness setting by the boolean fair parameter. However, fairness leads to reduced application throughput and as such should be used sparingly.
SemaphoreClass also supports non-blocking methods like
One of the major application of
Semaphore is while the creation of pooled resources like Database connections.
4. Download the Source Code
We have studied what semaphores are in Java, and how we can use them in our programs.
You can download the source code of this example here: java.util.concurrent.Semaphore – Semaphore Java Example
Last updated on June 01st, 2020