I am reading the book Java Concurrency in Practice. In a section about java.util.concurrent.Semaphore
, the below lines are present in the book. It is a comment about its implementation of "virtual permit" objects
The implementation has no actual permit objects, and
Semaphore
does not associate dispensed permits with threads, so a permit acquired in one thread can be released from another thread. You can think ofacquire
as consuming a permit andrelease
as creating one; aSemaphore
is not limited to the number of permits it was created with.
Can somebody explain this? I am having trouble understanding this. If we create a pool of fixed size, we create a fixed number of "permits". From the above statement, it looks like the "permits" can keep growing. Why is it designed this way?
There is no requirement that a thread that releases a permit must have acquired that permit by calling acquire().
Semaphore(int permits) It creates a Semaphore and parses the number of permits (initial number of permits available) as an argument. It specifies the number of threads that can share a resource at a time. The value of permits may be negative. In such a case, a release must occur before any acquires will be granted.
For signaling, the semaphore is initialized to 0; for mutual exclusion, the initial value is 1; for multiplexing, the initial value is a positive number greater than 1. To summarize, the general practice is that the initial value of the semaphore is the desired number of initial allowed concurrent accesses.
A semaphore can be released by any thread. A thread can call a wait function repeatedly on a mutex without blocking. However, if you call a wait function twice on a binary semaphore without releasing the semaphore in between, the thread will block.
I think that it means the times what we may require Semaphore as the times we released "extra" and plus the permits it created with.
Such as:
Semaphore s = new Semaphore(1); // one permit when initialize
s.acquire();
s.release();
s.release(); // "extra" release.
At this moment, this semaphore allows one permit originally and one "extra" permit
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With