信号量和同步
我不太明白 javadocs 中信号量描述中的以下内容。
注意,没有同步锁 当 acquire() 被调用时持有 会阻止一个项目被 回到了水池。 信号量 封装同步 需要限制对池的访问, 与任何同步分开 需要保持一致性 泳池本身。
有人可以帮助我理解这一点及其含义吗?
I could not quite understand the following from the semaphore description in javadocs.
Note that no synchronization lock is
held when acquire() is called as that
would prevent an item from being
returned to the pool. The semaphore
encapsulates the synchronization
needed to restrict access to the pool,
separately from any synchronization
needed to maintain the consistency of
the pool itself.
Can someone please help me understand this and its implications.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
信号量充当可用资源池深度的限制器;例如,容量为 10 的信号量最多允许 10 个线程同时获取它,并且任何其他尝试获取它的线程都将阻塞,直到其他线程之一释放它。
这与普通的互斥或监视器锁定有些不同,后者通常用于防止多个线程同时修改相同的变量并导致结果或程序状态不一致。
例如,考虑一个限制为 10 个连接的连接池。每个需要连接的线程将在其使用连接期间获取信号量(这可以防止太多线程同时请求连接),但是池对象在从其内部取出连接时也必须使用同步块或方法收集或将它们放回原处,以防止诸如丢失连接跟踪或由于两个不同线程同时请求而错误地将同一连接传递给两个不同线程之类的情况。
A semaphore acts as a limiter of available resource pool depth; for example, a semaphore with a capacity of 10 allows a maximum of 10 threads to acquire it at once, and any further threads that attempt to acquire it will block until one of the other threads releases it.
This is somewhat different from ordinary mutual exclusion or monitor locking, which is typically used to prevent more than one thread from simultaneously modifying the same variables and causing inconsistent results or program state.
Consider, for example, a connection pool with a limit of 10 connections in it. Each thread that needs a connection will acquire the semaphore for the duration of its use of a connection (which prevents too many threads asking for connections at once), but the pool object must also use synchronized blocks or methods when taking connections out of its internal collection or putting them back in, to prevent such things as losing track of connections or mistakenly handing the same connection to two different threads because they asked simultaneously.