'Why does Java allows to initialize semaphore with negative permit?
I'm not getting the rationale behind negative permits during initialization of Semaphore (java.util.concurrent.Semaphore).
I do know that calls to release() method may eventually make Semaphore's permit greater than equal to one (>=1) so that later on other thread can acquire permit. OR later on during program execution, Semaphore may have negative permits when more threads are awaiting for permits as they executed acquire() method..
However, I don't get any practical use-case where I'd be initializing Semaphore with negative permits.
Sample code for reference:
import java.util.concurrent.Semaphore;
public class SemaphoreDemo {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
Semaphore s = new Semaphore(-2);
System.out.println(s.availablePermits());
s.release(3); // adding 3 permits
System.out.println(s.availablePermits()); // now it has 1 permit
}
}
Solution 1:[1]
It may be useful in case you know that some resources already in use when you creating semaphore. For example those resources used in initialization.
Solution 2:[2]
Why shouldn't java allow for a negative number in a semaphore constructor? A semaphore is simply a mechanism to restrict access to some resource. If we want to restrict the access from the beginning, we might as well just initialize the semaphore with a negative value and make sure that no thread will touch that resource for now.
The javadoc is clear that:
@param permits the initial number of permits available.
This value may be negative, in which case releases must occur before any acquires will be granted.
You might be in a situation, where from the start, you need to wait for some resource to open up and become available before you start using it.
Ex: Imagine you 3 threads are building files that you need to work with. This operation takes time. Once all 3 threads are done, only then can you continue your work. You have to wait for these three threads to release the semaphore in order for you to continue your work. Now, this might not be a good solution to write-up, but at least it's possible to do with an initial semaphore of negative permits.
Another example with the same mantra is posted here
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | talex |
Solution 2 | mnestorov |