ReentrantReadWriteLock Read/write lock
ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock(); Thread 1readWriteLock.writeLock().lock(); Protected final Boolean tryAcquire(int acquires) {Thread current = thread.currentThread (); //state=0,c=0 int c = getState(); Int w= exclusiveCount(c); int w= exclusiveCount(c); int w= exclusiveCount(c);if(c ! = 0) {if(w == 0 || current ! = getExclusiveOwnerThread())return false;
if (w + exclusiveCount(acquires) > MAX_COUNT)
throw new Error("Maximum lock count exceeded");
setState(c + acquires);
return true; } // then go here, writerShouldBlock()=falseCAS sets state=1 and holds the lock thread to thread 1if(writerShouldBlock() || ! compareAndSetState(c, c + acquires))return false;
setExclusiveOwnerThread(current);
return true; } thread 1 successfully fetched thread 2 to read the lockreadWriteLock.writeLock().lock(); C =1,w! =0, but current! = getExclusiveOwnerThread(), returnsfalseThe lock fails, and the queue is blocked, similar to ReentrantLockif(w == 0 || current ! GetExclusiveOwnerThread () = getExclusiveOwnerThread()readWriteLock.readLock().lock(); Public final void acquireShared(int arg) {if (tryAcquireShared(arg) < 0)
doAcquireShared(arg);
}
protected final int tryAcquireShared(int unused) {
Thread current = Thread.currentThread();
int c = getState();
if(exclusiveCount(c) ! = 0 && getExclusiveOwnerThread() ! = current)return- 1; int r = sharedCount(c);if(! readerShouldBlock() && r < MAX_COUNT && compareAndSetState(c, c + SHARED_UNIT)) {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;
}
returnfullTryAcquireShared(current); } c=state=1, exclusiveCount(c)! = 0 &&getExclusiveOwnerThread() ! = current fortrueIf a write lock is added, it cannot be added to a read lock. The read lock and the write lock are mutually exclusive. Then it is queued and blocked.waitLet's say thread 1 has released the write lock, thread 2 has woken up, thread 2 has acquired the read lock and thread 3 has acquired the read lockreadWriteLock.writeLock().lock(); R = sharedCount(c); Is 16 bits higher than state, thread 2 has acquired the read lock, so r! =0, the following code refers to some records made after obtaining the read lock successfully. Like thread 2 is the firstReaderif (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++;
}
Copy the code