protected final int tryAcquireShared(int unused) {
/*
* Walkthrough:
* 1. If write lock held by another thread, fail.
* 2. Otherwise, this thread is eligible for
* lock wrt state, so ask if it should block
* because of queue policy. If not, try
* to grant by CASing state and updating count.
* Note that step does not check for reentrant
* acquires, which is postponed to full version
* to avoid having to check hold count in
* the more typical non-reentrant case.
* 3. If step 2 fails either because thread
* apparently not eligible or CAS fails or count
* saturated, chain to version with full retry loop.
*/
Thread current = Thread.currentThread();
int c = getState();
//1. 如果写锁已经被获取并且获取写锁的线程不是当前线程的话
// 线程获取读锁失败返回-1
if (exclusiveCount(c) != 0 &&
getExclusiveOwnerThread() != current)
return -1;
int r = sharedCount(c);
if (!readerShouldBlock() &&
r < MAX_COUNT &&
//2. 当前线程获取读锁
compareAndSetState(c, c + SHARED_UNIT)) {
//3. 下面的代码主要是新增的一些功能,比如getReadHoldCount()方法
//返回当前获取读锁的次数
if (r == 0) {
firstReader = current;
firstReaderHoldCount = 1;
} else if (firstReader == current) {
firstReaderHoldCount++;
} else {
HoldCounter rh = cachedHoldCounter;
if (rh == null || rh.tid != getThreadId(current))
cachedHoldCounter = rh = readHolds.get();
else if (rh.count == 0)
readHolds.set(rh);
rh.count++;
}
return 1;
}
//4. 处理在第二步中CAS操作失败的自旋已经实现重入性
return fullTryAcquireShared(current);
}
相关文章
- 03-0211.深入理解读写锁ReentrantReadWriteLock
- 03-02HDFS 深入理解 和 读写流程
- 03-02HDFS读写流程(适用于面试记忆、深入理解)
- 03-02深入理解SPDK 之二: 消息和无锁队列
- 03-02深入理解Zookeeper(二)如何通过zookeeper实现分布式锁
- 03-02JVM深入理解(五)-锁
- 03-02LVM&RAID 特点&区别,读写锁ReadWriteLock实现深入剖析
- 03-02JUC基础(21):ReentrantReadWriteLock读写锁
- 03-02深入理解(7)Java无锁CAS与Unsafe类及其并发包Atomic
- 03-02ReentrantReadWriteLock读写锁的使用