false
firstReader == current
extends
if (!isHeldExclusively())
ReadLock
cachedHoldCounter = rh = readHolds.get();
&&
||
写锁获取
true
AbstractQueuedSynchronizer
returnfalse
rh.count++;
判断是否是当前线程
return free;
判断当前线程是否是独占
setState(c + acquires);
FairSync
throw new IllegalMonitorStateException();
判断当前是否存在写锁
如果读锁加锁失败,再次尝试获取读锁
设置线程独有
return true;
int c = getState();
判断线程是否超过重入数16位最大(65535)
readHolds.set(rh);
firstReaderHoldCount = 1;
创建属于当前线程的计数器
if (exclusiveCount(c) != 0
return fullTryAcquireShared(current);
int r = sharedCount(c);
NonFairSync
if (writerShouldBlock()
判断重入次数是否==1
判断当前线程是否等于firstReader
==0
return false;
判断低16位是否为0
获取读锁的线程数
获取缓存的计数器
尝试加读锁
获取state状态
rh.tid != getThreadId(current)
将绑定的线程置为null
将当前线程获取读锁的线程数+1
if (firstReaderHoldCount == 1)
implements
HoldCounter
读锁获取
getExclusiveOwnerThread() != current)
int nextc = getState() - releases;
WriteLock
if (w + exclusiveCount(acquires) > MAX_COUNT)
获取当前线程
tryReleaseShared
将当前线程获取读锁重入次数+1
如果第一个获取锁的线程等于当前线程
implement
setExclusiveOwnerThread(current);
设置state值
tryAcquire
!=0
将第一个读锁指向当前线程
rh.count == 0
将state - 1
throw new Error(\"Maximum lock count exceeded\");
直接将当前线程获取读锁的次数置为null
如果写锁==0,那么一定存在读锁
设置state状态
firstReaderHoldCount++;
tryAcquireShared
将当前线程获取读锁的重入次数-1
Sync
firstReaderHoldCount--;
写锁的线程数
写锁释放
if (!readerShouldBlock()
r < MAX_COUNT &&
return 1;
firstReader = null;
公平与非公平
int w = exclusiveCount(c);
判断获取锁线程数是否超过最大,这里如果压测可能会超出
入队
判断state是否等于0,如果等于0说明没有写锁,则可以直接加锁
将当前线程获取锁重入次数赋值为1
if (w == 0)
returntrue
Lock
Thread current = Thread.currentThread();
setState(nextc);
ReentrantReadWriteLock
两种实现方式,公平/非公平
firstReader = current;
获取state值
setExclusiveOwnerThread(null);
if (c != 0)
NonfairSync
return-1
//获取缓存的计数器HoldCounter rh = cachedHoldCounter;//判断计数器为空 或者 当前线程ID与当前获取的不一致 if (rh == null || rh.tid != getThreadId(current))//再去获取 rh = readHolds.get();//将当前线程的重入次数取出 int count = rh.count; //如果小于等于1 if (count <= 1) { //直接将该计数器移除 readHolds.remove(); //如果count小于0,抛出异常 if (count <= 0) throw unmatchedUnlockException(); } //否则将该线程获取读锁的重入次数自减 --rh.count;
if (r == 0)
判断读锁获取次数
if (rh == null
current != getExclusiveOwnerThread()
tryRelease
ThreadLocalCounter
if (free)
boolean free = exclusiveCount(nextc) == 0;
HoldCounter rh = cachedHoldCounter;
不是
CAS设置state状态
if (firstReader == current)
大于
读锁释放
return hasQueuedPredecessors();
设置当前线程的获取读锁的重入次数
是