Home > database >  Why would a Thread aquire more than one permit of a semaphore?
Why would a Thread aquire more than one permit of a semaphore?

Time:08-08

If it's enough for a Thread to get access to a shared resource by acquiring just one permit through the call of acquire() so why it would want to call acquire(int permits)? Can you give an example of using acquire(int permits) ?

CodePudding user response:

Any resource that allows multiple instances: A license server may only allow 5 simultaneous users - so in theory a semaphore could be used with permits=5 (as well as tolerate multiple request threads). The 6th license request would fail to acquire until one is released.

CodePudding user response:

Imagine there is some communication protocol that transmits variable-length messages to a server, in asynchronous fashion, and for some reason or other, doesn't want to have more than 'N' kilobytes of unanswered messages outstanding. Perhaps it's some sort of fairness thing.

// Imagine a 'Message' has a request and
// an eventual response

final int MAX_OUTSTANDING_KB = 999;
Semaphore sema = new Semaphore(MAX_OUTSTANDING_KB);

void sendRequest(Message m) {
    int len = m.requestLength();
    int permits = (len   1023) / 1024; // round up
    m.setPermits(permits); // remember for release
    sema.acquire(permits); // possible wait here
    transmitBytes(m.requestBuffer());
}

void responseReceived(Message m) {
    sema.release(m.getPermits());
    process(m.responseBuffer());
}

This is a little contrived, but you should get the idea.

  •  Tags:  
  • java
  • Related