读写锁、StampLock详解
ReentrantReadWriteLock
简介
适用于读多写少的场景,特点是读读不互斥,读写与写写互斥。
基本使用
private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
private Lock r = readWriteLock.readLock();
private Lock w = readWriteLock.writeLock();
// 读操作上读锁
public Data get(String key) {
r.lock();
try {
// TODO 业务逻辑
}finally {
r.unlock();
}
}
// 写操作上写锁
public Data put(String key, Data value) {
w.lock();
try {
// TODO 业务逻辑
}finally {
w.unlock();
}
}
整体结构
读写锁有一个顶层规范接口ReadWriteLock
public interface ReadWriteLock {
Lock readLock();
Lock writeLock();
}
我们常用的ReentrantReadWriteLock
,它就实现了ReadWriteLock
接口,并创建了两个内部类分别代表读锁和写锁。同时还有公平锁与非公平锁
public class ReentrantReadWriteLock implements ReadWriteLock, java.io.Serializable {
private static final long serialVersionUID = -6992448646407690164L;
/** 读锁 */
private final ReentrantReadWriteLock.ReadLock readerLock;
/** 写锁 */
private final ReentrantReadWriteLock.WriteLock writerLock;
/** 同步器 同时还定义了三个内部类,用来满足公平锁与非公平锁的实现*/
final Sync sync;
public ReentrantReadWriteLock() {
this(false);
}
public ReentrantReadWriteLock(boolean fair) {
// 同步器 公平锁与非公平锁
// 这里先创建好了sync对象,然后再传给读写锁,为读写锁中的sync属性赋值
sync = fair ? new FairSync() : new NonfairSync();
// 读写锁
readerLock = new ReadLock(this);
writerLock = new WriteLock(this);
}
// 实现ReadWriteLock接口,重写的两个方法
public ReentrantReadWriteLock.WriteLock writeLock() {
return writerLock; }
public ReentrantReadWriteLock.ReadLock readLock() {
return readerLock; }
......
}
ReentrantReadWriteLock
结构如下图所示,定义了五个内部类
读锁与写锁
Sync
类继承了AbstractQueuedSynchronizer
类,而公平锁与非公平锁的两个类继承了Sync
类
而读锁与写锁则是实现了Lock
接口文章来源:https://www.toymoban.com/news/detail-403205.html
读锁:文章来源地址https://www.toymoban.com/news/detail-403205.html
到了这里,关于ReentrantReadWriteLock读写锁底层实现、StampLock详解的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!