gpt4 book ai didi

Java ReentrantReadWriteLock 请求

转载 作者:行者123 更新时间:2023-12-01 19:25:51 27 4
gpt4 key购买 nike

只是一个关于 Java 中的 ReadWriteLocks 的简单问题(特别是 ReentrantReadWriteLock 实现),因为我发现 sun 文档不清楚。

如果一个线程持有读锁,而另一个线程请求写锁,会发生什么情况?写锁线程是否必须等待所有当前持有的读锁被释放?另外,在授予并释放写锁之前,是否所有新的读锁请求都会被阻止?

谢谢

最佳答案

Javadoc 对此进行了解释:

This class does not impose a reader or writer preference ordering for lock access. However, it does support an optional fairness policy. When constructed as fair, threads contend for entry using an approximately arrival-order policy. When the write lock is released either the longest-waiting single writer will be assigned the write lock, or if there is a reader waiting longer than any writer, the set of readers will be assigned the read lock. When constructed as non-fair, the order of entry to the lock need not be in arrival order. In either case, if readers are active and a writer enters the lock then no subsequent readers will be granted the read lock until after that writer has acquired and released the write lock.

<小时/>

What happens if a read lock is held by a thread when a write lock is requested by another? Does the write lock thread have to wait for all currently held read-locks to be released?

是的,作者必须等待。但它只会等待当前持有的读锁。任何稍后到达的读者都会在作者之后排队。

Also, do all new read-lock requests get blocked until the write-lock is granted and released?

是的

关于Java ReentrantReadWriteLock 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1091388/

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