登录
    Technology changes quickly but people's minds change slowly.

锁的重入(Reentrancy)

技术宅 破玉 1473次浏览 0个评论

《Java concurrency in practice》一书说道,

When a thread requests a lock that is already held by another thread, the requesting thread blocks.
But because intrinsic locks are reentrant, if a thread tries to acquire a lock that it already holds, the request succeeds.
Reentrancy means that locks are acquired on a per-thread rather than per-invocation basis.
Reentrancy is implemented by associating with each lock an acquisition count and an owning thread.
When the count is zero, the lock is considered unheld. When a thread acquires a previously unheld lock,
the JVM records the owner and sets the acquisition count to one. If that same thread acquires the lock again,
the count is incremented, and when the owning thread exits the synchronized block, the count is decremented.
When the count reaches zero, the lock is released.

就是说Java的锁是可重入的,这个“重入”的实现方式是为每个锁关联一个计数器还有一个所有者线程。计数器值为0是,锁未被任何线程持有,当有新的线程请求这个未被持有的锁时,JVM就会记录下这个锁的持有者,并把计数器值记为1。如果,同一个线程再次请求这个锁时,计数器的值就会递增;线程退出同步代码块时,计数器递减。计数器值变为0时,锁被释放。“重入”意味着锁的粒度是以“每线程”为基本单位的,而不是“每调用”。可重入就意味着:线程可以进入任何一个它已经拥有的锁所同步着的代码块。
参考链接:可重入与不可重入


华裳绕指柔, 版权所有丨如未注明 , 均为原创|转载请注明锁的重入(Reentrancy)
喜欢 (0)
发表我的评论
取消评论
表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址