How do we implement semaphore in Java - Mar Java Mit Java

How do we implement semaphore in Java

A semaphore is a particular lock that allows more than one thread to access the target object. It’s like having more keys, so that many people can unlock the door.
This is how a semaphore would look like if we had to write it in Java:

 
public class Semaphore {
	private int counter = 0;
	private int max   = 0;
 
	public Semaphore(int max){
		this.max = max;
	}
 
	public synchronized void take() throws InterruptedException{
		while(this.counter == max) wait();
		this.counter++;
		this.notify();
	}
 
	public synchronized void release() throws InterruptedException{
		while(this.counter == 0) wait();
		this.counter--;
		this.notify();
	}
}

In this example we shall show you how to use a Semaphore for limiting URL connections. We have implemented a class, ConnectionLimiter that uses a Semaphore

public class ConnectionLimiter {
   private final Semaphore semaphore;
 
   private ConnectionLimiter(int maxConcurrentRequests) {
 
 semaphore = new Semaphore(maxConcurrentRequests);
   }
 
   public URLConnection acquire(URL url) throws InterruptedException,IOException {
 
 semaphore.acquire();
 
 return url.openConnection();
   }
 
   public void release(URLConnection conn) {
 
 try {
 
     /*
 
     * ... clean up here
 
     */
 
 } finally {
 
     semaphore.release();
 
 }
   }
}

Uday Ogra

Connect with me at http://facebook.com/tendulkarogra and lets have some healthy discussion :)

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *