问题描述
我需要写入线程优先于读取线程访问临界区,我可以使用 ReadWriteLock 接口来做到这一点吗?
解决方法
虽然不直接使用 ReadWriteLock
,但最简单的内置方法可能是 Semaphore
,它确实支持公平性。创建一个公平 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);
}
}