信号量如何以及为什么会发出比初始化更多的许可证? [英] How and why can a Semaphore give out more permits than it was initialized with?
问题描述
我正在读Java并发实践一书。在有关 java.util.concurrent.Semaphore
的部分中,以下行显示在书中。它是关于其实现虚拟许可对象的注释
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
实现没有实际的permit对象,
信号量
不会将分配的许可证与线程相关联,因此在
一个线程中获取的许可证可以从另一个线程释放。您可以认为
获取
为使用许可证,release
为创建许可证; a
Semaphore
不限于创建的许可数。
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?
推荐答案
而不是交出许可对象,当新许可证被创建时,计数器增加,当许可证被返回时,计数器被减少。
Instead of "handing out" permit objects, the implementation just has a counter. When a new permit is "created" the counter is increased, when a permit is "returned" the counter is decreased.
这使得比创建实际对象所有的时间。
This makes for much better performance than creating actual objects all the time.
权衡是,Semaphore本身不能检测某些种类的编程错误(例如未授权的许可现金或信号量泄漏)。作为编码者,你必须确保遵守自己的规则。
The tradeoff is that the Semaphore itself cannot detect certain kinds of programming errors (such as unauthorized permit cash-ins, or semaphore leaks). As the coder, you have to make sure to follow the rules on your own.
这篇关于信号量如何以及为什么会发出比初始化更多的许可证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!