Semaphore
About
Semaphore is utility under java.util.concurrent package. I can initialize it with integer count like
Semaphore tokens = new Semaphore(1); // Here count = 1
This count is no of tokens that semaphore will have.
Semaphore is used to control a number of threads that can access a certain resource or perform given action at the same time.
Threads can acquire tokens by calling semaphore.acquire() and release token by calling semaphore.release() when they are done with them. If no token is available then the thread will be blocked until one is available and release method returns token to the semaphore.
Use Case
Semaphore is useful for implementing resource pool such as database connection pools.
Example: The Bridge is very old and only one train can pass at a time.The train can come from both sides. Again but only one can pass at a time. Let's assume train comes from both sides and stops at the bridge, waiting for a signal. In this case, only one train can be signaled at a time to avoid a collision.
class BridgeCrossingTask implements Runnable {
private final Semaphore signal;
public BridgeCrossingTask(Semaphore signal) {
this.signal = signal;
}
@Override
public void run() {
System.out.println("Train " + Thread.currentThread().getName() + " reached at rail bridge and waiting for signal.");
try {
signal.acquire();
System.out.println("Train " + Thread.currentThread().getName() + " got signal, is passing and will take 10 sec");
Thread.sleep(10000);
} catch(InterruptedException e) {
Thread.interrupted();
} finally {
System.out.println("Train " + Thread.currentThread().getName() + " is passed.");
signal.release();}} }
public class SemaphoreExample {
public static void main(String[] args) {
Semaphore passToken = new Semaphore(1);
BridgeCrossingTask task = new BridgeCrossingTask(passToken);
new Thread(task,"Rajdhani").start();
new Thread(task,"Shatabdi").start();
}
}
In this SemaphoreExample class creates Semaphore with 1 count for signaling (only one train can pass bridge at a time), two threads as Trains "Rajdhani" and "Shatabdi" (famous Indian trains). Calling BridgeCrossingTask class.
BridgeCrossingTask class implements Runnable and having logic for the train to cross the bridge. Here, one train will acquire a signal (Semaphore token) and cross the bridge. Another train will be blocked on Semaphore for a token to be available (aka signal).
The first train will pass the bridge and return token to Semaphore. Now, this can be acquired by the second Train to cross the bridge.
Result will be like:-
This way Semaphore can help avoid a collision on the bridge.
Comments
Post a Comment