gpt4 book ai didi

java - ReentrantReadWriteLock 中的公平锁定

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:23:00 25 4
gpt4 key购买 nike

在 B. Goetz 的 Java Concurrency In Practice 中,第 13.5 节说:

In Java 5.0, the read lock behaves more like a semaphore than a lock, maintaining only the count of active readers, not their identities. The behavior was changed in Java 6 to keep track also of which threads have been granted the read lock6.

6 One reason for this change is that under java 5.0, the lock implementation cannot distinguish between a thread requesting the read lock for the first time and reentrant lock request, which would make fair read-write lock deadlock-prone.

我的问题是公平有什么问题?为什么屏蔽了非公平读写锁导致死锁呢?

你能解释一下他的意思吗?我的意思是在什么情况下,Java 5 下的公平 读写锁会导致死锁?如果它的行为像一个 Semaphore,为什么公平的 Semaphore 不会导致死锁?

最佳答案

如果实现不知道请求线程是否已经拥有锁,在公平锁定策略的情况下,来自同一线程的新请求将排在先前请求之后,可能来自其他线程。

如果在此重入请求之前有来自其他线程的写请求,则它们无法前进,因为持有锁的线程也被阻塞以等待其重入请求。导致死锁。

不公平的锁定策略不会遇到这个问题,因为重入请求可以跳队列(打断)并且不需要等待先前的请求。

信号量不会遇到这个问题,因为它不是可重入的。

关于java - ReentrantReadWriteLock 中的公平锁定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37136917/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com