Java ReentrantReadWriteLock 请求

发布于 07-25 20:51 字数 207 浏览 7 评论 0原文

只是一个关于 Java 中的 ReadWriteLocks(特别是 ReentrantReadWriteLock 实现)的简单问题,因为我没有找到清晰的 sun 文档。

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

谢谢

Just a quick question about ReadWriteLocks in Java (specifically the ReentrantReadWriteLock implementation) as I don’t find the sun documentation clear.

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?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一紙繁鸢2024-08-01 20:51:08

Javadoc 对此进行了解释:

此类不强加读者
或作者偏好排序
锁定访问。 不过,它确实支持
可选的公平性
政策。 当构建公平时,
线程使用一个竞争条目
关于到货订单政策。
当写锁被释放时
要么是等待时间最长的单曲
writer 将被分配 write
锁定,或者如果有读者在等待
比任何作家都长,
读者将被分配阅读
锁。 当构建为非公平时,
进入锁需要的顺序
不按到达顺序。 在任一
情况下,如果读者很活跃并且
writer 输入锁然后没有
后续读者将被授予
读锁定直到该写入者之后
已获取并释放写入
锁定。


如果一个线程持有读锁,而另一个线程请求写锁,会发生什么情况? 写锁线程是否必须等待所有当前持有的读锁被释放?

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

此外,在授予并释放写锁之前,所有新的读锁请求是否都会被阻止?

是的

The Javadoc explains this:

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?

Yes, the writer will have to wait. But it will only wait for the currently held read locks. Any readers arriving later will queue after the writer.

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

Yes

生生漫2024-08-01 20:51:08

ReadWriteLock 不能同时持有写锁和读锁。 例如,在持有读锁时请求写锁将导致阻塞或失败。

A ReadWriteLock cannot have a write lock held at the same time as read locks. Requests for, say, a write lock when a read lock is held will result in blocking or a fail.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文