A 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 into 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 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.)
The java.util.concurrent.Semaphore Class implements a counting Semaphore.
Features of Semaphore Class in Java
The Semaphore Class constructor takes a int parameter, 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, the fairness leads to reduced application throughput and as such should be used sparingly.
The Semaphore Class also supports non-blocking methods like tryacquire() and tryacquire(int permits).
Example,
import java.util.concurrent.Semaphore;
public class SemaphoreDemo {
Semaphore semaphore = new Semaphore(10);
public void printLock() {
try {
semaphore.acquire();
System.out.println("Locks acquired");
System.out.println("Locks remaining >> "
+ semaphore.availablePermits());
} catch (InterruptedException ie) {
ie.printStackTrace();
} finally {
semaphore.release();
System.out.println("Locks Released");
}
}
public static void main(String[] args) {
final SemaphoreDemo semaphoreDemo = new SemaphoreDemo();
Thread thread = new Thread() {
@Override
public void run() {
semaphoreDemo.printLock();
}
};
thread.start();
}
}
OUTPUT
Locks acquired
Locks remaining >> 9
Locks Released
No comments:
Post a Comment