java - 写锁优先访问java readWrite锁中的关键区域?
问题描述
我需要编写器线程优先于读取器线程访问关键区域,我可以使用 ReadWriteLock 接口来执行此操作吗?
解决方案
虽然不是直接使用 a ReadWriteLock
,但最简单的内置方法可能是 a Semaphore
,它确实支持公平性。创建一个fair Semaphore
,(有效)无限数量permis
就足够了:
private static final Semaphore lock = new Semaphore(Integer.MAX_VALUE, true);
public void doReadLocked() throws InterruptedException {
// 'Read' lock only acquires one permit, but since there are A LOT,
// many of them can run at once.
lock.acquire();
try {
// Do your stuff in here...
} finally {
// Make sure you release afterwards.
lock.release();
}
}
public void doWriteLocked() throws InterruptedException {
// 'Write' lock demands ALL the permits. Since fairness is set, this
// will 'take priority' over other waiting 'read'ers waiting to acquire
// permits.
lock.acquire(Integer.MAX_VALUE);
try {
// Do your stuff in here...
} finally {
// Make sure you release afterwards.
lock.release(Integer.MAX_VALUE);
}
}
推荐阅读
- menu - Flutter中带有3页的自定义网格菜单
- idris - 伊德里斯:证明复数乘法是结合的
- android - 是否有任何监听器可以从手机存储中删除操作?
- android - 特定行的数据库查询
- bash - 用不同的随机字符替换十六进制字符(可以使用 awk 吗?)
- php - 使用 eloquent un laravel 后显示 Empty
- php - Symfony4 docker原则不创建数据库
- html - 放大图像时不缩放 img 父级的宽度
- vb.net - 根据2个文本框VB.Net中的时差计算要支付的金额
- sql - 我在没有用户的 heroku 应用程序中创建了一个 PostGres 数据库。现在我已将用户添加到我的应用程序中。如何将数据库复制到其中一位用户?