A semaphore is a technique used to restrict the number of simultaneous threads on a shared resource up to a maximum number. It maintains a counter called permits which keeps track of the number of resources available. Semaphore is just a gatekeeper guarding the resources .If permits available then grants access to shared resources otherwise ask the threads to wait.
Example:
Lets understand the usage with a simple program below. Here we have 2 printers and 10 threads are trying to access the same printers. Each thread will be able to use the printer only if any printer is available.
1 2 3 4 5 6 7 8 9 10 11 12 |
import java.util.concurrent.Semaphore; public class SemaphoreDemo{ public static void main(String[] args) { Semaphore printerSem=new Semaphore(2); PrinterSemaphore printerSemObj=new PrinterSemaphore(printerSem); for(int i=1;i<=10;i++){ new Thread(printerSemObj, "User"+i).start(); } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import java.util.concurrent.Semaphore; public class PrinterSemaphore implements Runnable{ Semaphore printerSem; PrinterSemaphore(Semaphore printerSem){ this.printerSem=printerSem; } @Override public void run() { try { printerSem.acquire(); System.out.println(Thread.currentThread().getName()+" is Using the printer"); Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+" Releasing the printer"); printerSem.release(); } } |
Output:
User1 is Using the printer
User2 is Using the printer
User1 Releasing the printer
User2 Releasing the printer
User3 is Using the printer
User4 is Using the printer
User3 Releasing the printer
User4 Releasing the printer
User5 is Using the printer
User7 is Using the printer
User5 Releasing the printer
User7 Releasing the printer
User6 is Using the printer
User9 is Using the printer
User9 Releasing the printer
User6 Releasing the printer
User8 is Using the printer
User10 is Using the printer
User8 Releasing the printer
User10 Releasing the printer
Here you can notice that only two threads are getting access to the printer at a time.
Important methods :
acquire():If permits are available then threads can access shared resources by calling acquire() method.
release(): Once the thread is finished using resource, it returns back the permit using release() method of Semaphore
availablePermits(): This method returns the available number of permit at any time.
Real time use cases :
- Consider an ATM cubicle with 2 ATM machines and can allow only 2 people to access machine simultaneously.
- For implementing Producer Consumer pattern
- One book can be issued to only one reader at a time in a Library.
Leave a Reply