RReadWriteLock rwlock = redisson.getReadWriteLock("myLock");
RLock lock = rwlock.readLock();
// or
RLock lock = rwlock.writeLock();
// traditional lock method
lock.lock();
// or acquire lock and automatically unlock it after 10 seconds
lock.lock(10, TimeUnit.SECONDS);
// or wait for lock aquisition up to 100 seconds
// and automatically unlock it after 10 seconds
boolean res = lock.tryLock(100, 10, TimeUnit.SECONDS);
if (res) {
try {
...
} finally {
lock.unlock();
}
}
源码分析
首先我们看一下 Redisson#getReadWriteLock方法:
@Override
public RReadWriteLock getReadWriteLock(String name) {
return new RedissonReadWriteLock(commandExecutor, name);
}
什么是读写锁?
维基百科上 读写锁 定义:
实现方案
1、使用两把互斥锁
Michel Raynal使用两把互斥锁与一个整数计数器实现。计数器b跟踪被阻塞的读线程。互斥锁r保护b,供读者使用。互斥锁g (指"global")确保写操作互斥。
注:实现是读操作优先。
读者加锁伪代码: Begin Read
End Read
写者加锁伪代码: Begin Write
End Write
2、使用条件变量与互斥锁
可使用条件变量c与普通的互斥锁m、整型计数器r(表示正在读的个数)与布尔标志g(表示正在写)来实现读写锁。 lock-for-read操作:
lock-for-write操作:
lock-for-read与lock-for-write各自有自己的逆操作。
应用场景
读写锁的含义是准确的:是一种 读共享,写独占的锁。
读写锁的特性:
互斥原则:
因而适用于读多写少的场景。
Redisson中读写锁实现
关于读写锁,大家应该都了解JDK中的ReadWriteLock, 当然Redisson也有读写锁的实现。
所谓读写锁,就是多个客户端同时加读锁,是不会互斥的,多个客户端可以同时加这个读锁,读锁和读锁是不互斥的
Redisson中使用RedissonReadWriteLock来实现读写锁,它是RReadWriteLock的子类,具体实现读写锁的类分别是:RedissonReadLock和RedissonWriteLock
官方文档中给出的Redisson读写锁使用示例:
源码分析
首先我们看一下 Redisson#getReadWriteLock方法:
RedissonReadWriteLock 是 RReadWriteLock 接口的唯一实现类,如下:
一、Redisson 读锁逻辑
Redisson 读锁相关的逻辑封装在 RedissonReadLock 类中,如下:
1、加锁逻辑
首先,我们看看加锁逻辑:
加锁lua脚本如下:
2、解锁逻辑
对应的lua脚本如下:
Redisson 写锁逻辑
Redisson 写锁相关的逻辑封装在 RedissonWriteLock类中,如下:
加锁逻辑:
解锁逻辑: