合理锁定ReeantrantReadWriteLock [英] Fair locking in ReeantrantReadWriteLock

查看:68
本文介绍了合理锁定ReeantrantReadWriteLock的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

B.Goetz在《 Java并发实践》中第13.5节说:

In Java Concurrency In Practice by B. Goetz, section 13.5 said:

在Java 5.0中,读锁的行为更像是信号灯,而不是锁, 仅保留活跃读者的人数,而不保留其身份. 在Java 6中更改了行为,以跟踪哪些线程 已被授予读取锁定6.

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进行此更改的原因之一是在Java 5.0下,锁 实现无法区分请求读取的线程 首次锁定和可重入的锁定请求,会发出 一般 .读写锁容易发生死锁.

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.

我的问题是公平有什么问题?为什么不公平的读写锁可以避免死锁?

My question is what's wrong with fairness? Why was the unfair read-write lock shielded from the deadlock?

您能解释一下他的意思吗?我的意思是在Java 5下 fair 的读写锁定在什么情况下会导致死锁?如果行为像Semaphore一样,为什么合理的Semaphore不会造成死锁?

Could you explain what he meant? I mean in which circumstances does a fair read-write lock under Java 5 cause a deadlock? And if it behaved like a Semaphore why didn't the fair Semaphore cause a deadlock?

推荐答案

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

If the implementation does not know whether a requesting thread already has the lock, in case of a fair locking strategy new request from the same thread would be queued after prior requests, possibly from other threads.

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

If there are write requests from other threads preceding this reentrant request, they cannot advance since the thread holding the lock is also blocked waiting for its reentrant request. Resulting in deadlock.

不公平的锁定策略不会遇到此问题,因为可重入请求可以跳过队列(插入),并且无需等待先前的请求.

An unfair locking strategy does not suffer from this problem as the reentrant request can jump the queue (barging) and doesn't need to wait for prior requests.

信号量不会遭受此问题的困扰,因为它并不意味着可以重入.

Semaphore does not suffer from this problem because it is not meant to be reentrant.

这篇关于合理锁定ReeantrantReadWriteLock的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆