开发者

Using semaphore to control number of threads

How can I make use of Semapho开发者_如何学Pythonre class in order to control number of threads that have an access to an object?


  • Initialize the Semaphore with the max number of alowed threds,
  • reduce the semaphore counter by one if a thread enters the restricted area
  • increse the semaphore counter by one if the thred leaves the restricted area


One more good thing about using semaphore to control access to resouce is you can resize your semaphore at runtime. For eg you can have some use case where you want to allow more user to access resource based on some business logic and then reduce it again. Sample code for re sizable semaphore

public class ResizeableSemaphore extends Semaphore
{

    private static final long serialVersionUID = 1L;
    private int permit;
    public ResizeableSemaphore(int permit) {
        super(permit);
        this.permit=permit;
    }       

    public synchronized void resizeIfRequired(int newPermit)
    {
        int delta = newPermit - permit;
        if(delta==0) return;
        if(delta > permit) this.release(delta); // this will increase capacity
        if(delta < 0) this.reducePermits(Math.abs(delta));
        this.permit=newPermit;
    }   
}


This is a great example of how Semaphore can be used to limit concurrent access to an object:

http://technicalmumbojumbo.wordpress.com/2010/02/21/java-util-concurrent-java-5-semaphore/

The key points being:

  • When you construct the Semaphore, you can declare the max concurrency (i.e., number of threads allowed to access concurrently)
  • You require each thread to attempt to acquire() the Semaphore; let the Semaphore keep track of concurrent access


Just use:

java.util.concurrent.Semaphore

there's an extensive example on how to use it in the javadoc:

http://download.oracle.com/javase/6/docs/api/java/util/concurrent/Semaphore.html


Perhaps you could read the answer to this question, and have a look at this example

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜