ReentrantReadWriteLock原始碼分析
ReentrantLock中,執行緒都是以獨佔的方式來獲得鎖,但是在很多情況下,比如讀多寫少的情況,使用獨佔的方式明顯不合適,讀和讀之間不會修改共享資源,可以保證不會出現問題,這種情況下使用ReentrantReadWriteLock會更合適。讀執行緒之間使用共享鎖,寫寫和寫讀之間使用獨佔鎖。ReentrantReadWriteLock的類結構如下圖所示:
其中Syn實現了AQS中的一些比較重要的方法,比如lock和release,這裡包括獨佔的方式和共享的方式兩種。NonfairSyn和FairSyn是公平鎖和非公平鎖的實現,主要包括兩個方法。ReadLock和WriteLock是對Syn類中的方法進行再一次的封裝,函式體都非常簡單。
特性
1.公平性:讀操作之間不互斥,所以沒有公平非公平這麼一說。寫操作在非公平鎖中,寫鎖總是最先獲得鎖。而在公平鎖中,只根據在CLH佇列中等待的時間來分配鎖。
2.重入性:讀操作獲得讀鎖之後可以再次獲得讀鎖,寫鎖同理。但是讀鎖不能被寫鎖重入,寫鎖可以獲得讀鎖,這就是鎖降級。
3.可中斷:提供可以響應中斷的鎖。
引數及建構函式
/** 通過內部類來獲得讀鎖 */
private final ReentrantReadWriteLock.ReadLock readerLock;
/** 獲得寫鎖*/
private final ReentrantReadWriteLock.WriteLock writerLock;
/** Performs all synchronization mechanics */
final Sync sync;
/**
* 預設是非公平鎖,因為這樣吞吐量更大.
*/
public ReentrantReadWriteLock() {
this(false);
}
/**
* 可以在建構函式中設定公平或者是非公平
* @param fair {@code true} if this lock should use a fair ordering policy
*/
public ReentrantReadWriteLock(boolean fair) {
sync = fair ? new FairSync() : new NonfairSync();
readerLock = new ReadLock(this);
writerLock = new WriteLock(this);
}
和reentrantLock不一樣的地方在於把原來的state拆成了兩份。
/*
*通過將state狀態分為高16位和低16位來分別代表讀鎖的佔有量和寫鎖的佔有量
*/
static final int SHARED_SHIFT = 16;
static final int SHARED_UNIT = (1 << SHARED_SHIFT);
static final int MAX_COUNT = (1 << SHARED_SHIFT) - 1;
static final int EXCLUSIVE_MASK = (1 << SHARED_SHIFT) - 1;
/** 獲得共享鎖佔有的次數 */
static int sharedCount(int c) { return c >>> SHARED_SHIFT; }
/** 獲取獨佔鎖重入的次數 */
static int exclusiveCount(int c) { return c & EXCLUSIVE_MASK; }
寫鎖的讀取和釋放
寫鎖由於是獨佔鎖,其獲取和釋放相對讀鎖更加簡單。寫鎖的獲取和釋放都在Syn中實現。
首先會獲得當前鎖的數量,然後在通過位操作獲得相應的寫鎖個數,並根據相應條件進行判斷是否這個執行緒可以獲得寫鎖。
/**
* 獲得鎖成功則退出,不成功則新增節點到CLH佇列尾部,然後執行acquireQueued迴圈嘗試獲取鎖,這裡和reentrantLock 類似。
*
* @param arg the acquire argument. This value is conveyed to
* {@link #tryAcquire} but is otherwise uninterpreted and
* can represent anything you like.
*/
public final void acquire(int arg) {
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
protected final int tryAcquireShared(int unused) { //嘗試獲取資源 /* * */
Thread current = Thread.currentThread();
int c = getState();
if (exclusiveCount(c) != 0 && //當期寫鎖不為0 或者是寫鎖佔有了執行緒 返回-1
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;//讀鎖個數為0 設定頭讀節點和持有數量
} 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;
}
return fullTryAcquireShared(current);//讀鎖被阻塞導致的失敗,繼續執行下面函式來獲取鎖 }
}
protected final boolean tryAcquire(int acquires) {
/*
* Walkthrough:
* 1. 讀鎖個數不是0或者寫鎖個數不是0或者當前執行緒不是持有鎖的執行緒,失敗。
* 2. 如果鎖個數大於最大值,失敗
* 3. Otherwise, this thread is eligible for lock if
* it is either a reentrant acquire or
* queue policy allows it. If so, update state
* and set owner.
*/
Thread current = Thread.currentThread();
int c = getState();//獲取鎖的個數
int w = exclusiveCount(c);//獲取低十六位,也就是寫鎖的數量。
if (c != 0) {
// (Note: if c != 0 and w == 0 then shared count != 0)
if (w == 0 || current != getExclusiveOwnerThread())
return false;//讀鎖不為0,寫鎖為0,失敗
if (w + exclusiveCount(acquires) > MAX_COUNT)
throw new Error("Maximum lock count exceeded");//個數太多,失敗
// Reentrant acquire
setState(c + acquires);//其他都是成功,返回新的狀態值
return true;
}
if (writerShouldBlock() || //鎖的個數為0 判斷是否需要阻塞 ,write總是返回false
!compareAndSetState(c, c + acquires))
return false;
setExclusiveOwnerThread(current);//設定排他執行緒。
return true;
}
寫鎖釋放也比較簡單,判斷執行緒是否正確,判斷鎖的個數是否為0. /*
* Note that tryRelease and tryAcquire can be called by
* Conditions. So it is possible that their arguments contain
* both read and write holds that are all released during a
* condition wait and re-established in tryAcquire.
*/
protected final boolean tryRelease(int releases) {
if (!isHeldExclusively())//如果當前執行緒不是持有執行緒則丟擲異常。
throw new IllegalMonitorStateException();
int nextc = getState() - releases;//重新計算鎖的個數
boolean free = exclusiveCount(nextc) == 0;//鎖的個數中低16位鎖個數為0 則設定排他執行緒為空
if (free)
setExclusiveOwnerThread(null);
setState(nextc);
return free;
}
讀鎖的獲取比較複雜。下面是讀鎖獲取的簡單流程。
/**
* 忽略中斷,以共享的模式獲取鎖 Implemented by
* first invoking at least once {@link #tryAcquireShared},
* returning on success. Otherwise the thread is queued, possibly
* repeatedly blocking and unblocking, invoking {@link
* #tryAcquireShared} until success.
*
* @param arg the acquire argument. This value is conveyed to
* {@link #tryAcquireShared} but is otherwise uninterpreted
* and can represent anything you like.
*/
public final void acquireShared(int arg) {
if (tryAcquireShared(arg) < 0)//嘗試獲取鎖,如果沒有獲得,就做一些嘗試操作
doAcquireShared(arg);
}
/**
* Full version of acquire for reads, that handles CAS misses
* and reentrant reads not dealt with in tryAcquireShared.
*/
final int fullTryAcquireShared(Thread current) {
/*
* This code is in part redundant with that in
* tryAcquireShared but is simpler overall by not
* complicating tryAcquireShared with interactions between
* retries and lazily reading hold counts.
*/
HoldCounter rh = null;
for (;;) {
int c = getState();
if (exclusiveCount(c) != 0) {
if (getExclusiveOwnerThread() != current)//寫鎖被分配,不是當前執行緒,失敗
return -1;
// else we hold the exclusive lock; blocking here
// would cause deadlock.
} else if (readerShouldBlock()) {//寫鎖為0 讀鎖幾遍被阻塞也要執行,不然死鎖
// Make sure we're not acquiring read lock reentrantly
if (firstReader == current) {
// assert firstReaderHoldCount > 0;
} else {//頭讀節點不是當前執行緒
if (rh == null) {
rh = cachedHoldCounter;
if (rh == null || rh.tid != getThreadId(current)) {
rh = readHolds.get();
if (rh.count == 0)
readHolds.remove();
}
}
if (rh.count == 0)
return -1;
}
}//成功獲取讀鎖,如果是頭讀節點則狀態加一,否則和tryAcquired成功獲取鎖一樣。
if (sharedCount(c) == MAX_COUNT)
throw new Error("Maximum lock count exceeded");
if (compareAndSetState(c, c + SHARED_UNIT)) {//設定狀態
if (sharedCount(c) == 0) {
firstReader = current;
firstReaderHoldCount = 1;
} else if (firstReader == current) {
firstReaderHoldCount++;
} else {
if (rh == null)
rh = cachedHoldCounter;
if (rh == null || rh.tid != getThreadId(current))
rh = readHolds.get();
else if (rh.count == 0)
readHolds.set(rh);
rh.count++;
cachedHoldCounter = rh; // cache for release
}
return 1;
}
}
}
/**
* 讀鎖獲取資源失敗後,新增這個執行緒作為一個節點放在後面,然後不斷獲取前驅節點,當前驅節點是head節點時,嘗試獲取資源
* 否則,判斷當前執行緒是不是應該阻塞,然後阻塞之。
*/
private void doAcquireShared(int arg) {
final Node node = addWaiter(Node.SHARED);
boolean failed = true;
try {
boolean interrupted = false;
for (;;) {
final Node p = node.predecessor();
if (p == head) {
int r = tryAcquireShared(arg);
if (r >= 0) {
setHeadAndPropagate(node, r);
p.next = null; // help GC
if (interrupted)
selfInterrupt();
failed = false;
return;
}
}
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
interrupted = true;
}
} finally {
if (failed)
cancelAcquire(node);
}
}
讀鎖的釋放相對簡單,首先嚐試釋放資源,如果可以的話嘗試喚醒後繼節點。嘗試釋放資源的過程中,如果當前節點是頭讀節點,並且持有鎖的數量為1,那麼釋放資源之後頭讀節點就是null了,否則將持有節點數量減一。
/**
* Releases in shared mode. Implemented by unblocking one or more
* threads if {@link #tryReleaseShared} returns true.
*
* @param arg the release argument. This value is conveyed to
* {@link #tryReleaseShared} but is otherwise uninterpreted
* and can represent anything you like.
* @return the value returned from {@link #tryReleaseShared}
*/
public final boolean releaseShared(int arg) {
if (tryReleaseShared(arg)) {
doReleaseShared();
return true;
}
return false;
}
protected final boolean tryReleaseShared(int unused) {
Thread current = Thread.currentThread();
if (firstReader == current) {
// assert firstReaderHoldCount > 0;
if (firstReaderHoldCount == 1)
firstReader = null;
else
firstReaderHoldCount--;
} else {
HoldCounter rh = cachedHoldCounter;
if (rh == null || rh.tid != getThreadId(current))
rh = readHolds.get();
int count = rh.count;
if (count <= 1) {
readHolds.remove();
if (count <= 0)
throw unmatchedUnlockException();
}
--rh.count;
}
for (;;) {
int c = getState();
int nextc = c - SHARED_UNIT;
if (compareAndSetState(c, nextc))
// Releasing the read lock has no effect on readers,
// but it may allow waiting writers to proceed if
// both read and write locks are now free.
return nextc == 0;//如果鎖為0,可以喚醒後面的寫鎖了。
}
}
/**
* Release action for shared mode -- signals successor and ensures
* propagation. (Note: For exclusive mode, release just amounts
* to calling unparkSuccessor of head if it needs signal.)
*/
private void doReleaseShared() {
/*
*喚醒後繼節點
*/
for (;;) {
Node h = head;
if (h != null && h != tail) {
int ws = h.waitStatus;
if (ws == Node.SIGNAL) {
if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0))
continue; // loop to recheck cases
unparkSuccessor(h);
}
else if (ws == 0 &&
!compareAndSetWaitStatus(h, 0, Node.PROPAGATE))
continue; // loop on failed CAS
}
if (h == head) // loop if head changed
break;
}
}
參考資料:
https://my.oschina.net/adan1/blog/158107
https://www.jianshu.com/p/d47fe1ec1bb3
https://www.jianshu.com/p/9f98299a17a5(寫的很詳細)
http://ifeve.com/juc-reentrantreadwritelock/
相關文章
- ReentrantReadWriteLock原始碼分析及理解原始碼
- Java 讀寫鎖 ReentrantReadWriteLock 原始碼分析Java原始碼
- 原始碼分析:ReentrantReadWriteLock之讀寫鎖原始碼
- ReentrantReadWriteLock原始碼解析原始碼
- 【JUC】JDK1.8原始碼分析之ReentrantReadWriteLock(七)JDK原始碼
- Java併發指南10:Java 讀寫鎖 ReentrantReadWriteLock 原始碼分析Java原始碼
- 深入淺出ReentrantReadWriteLock原始碼解析原始碼
- java原始碼-ReentrantReadWriteLock寫鎖介紹Java原始碼
- Java併發之ReentrantReadWriteLock原始碼解析(一)Java原始碼
- Java併發之ReentrantReadWriteLock原始碼解析(二)Java原始碼
- JUC原始碼學習筆記6——ReentrantReadWriteLock原始碼筆記
- Retrofit原始碼分析三 原始碼分析原始碼
- 集合原始碼分析[2]-AbstractList 原始碼分析原始碼
- 集合原始碼分析[1]-Collection 原始碼分析原始碼
- 集合原始碼分析[3]-ArrayList 原始碼分析原始碼
- Guava 原始碼分析之 EventBus 原始碼分析Guava原始碼
- Android 原始碼分析之 AsyncTask 原始碼分析Android原始碼
- 【JDK原始碼分析系列】ArrayBlockingQueue原始碼分析JDK原始碼BloC
- 以太坊原始碼分析(36)ethdb原始碼分析原始碼
- 以太坊原始碼分析(38)event原始碼分析原始碼
- 以太坊原始碼分析(41)hashimoto原始碼分析原始碼
- 以太坊原始碼分析(43)node原始碼分析原始碼
- 以太坊原始碼分析(52)trie原始碼分析原始碼
- 深度 Mybatis 3 原始碼分析(一)SqlSessionFactoryBuilder原始碼分析MyBatis原始碼SQLSessionUI
- 以太坊原始碼分析(51)rpc原始碼分析原始碼RPC
- 全網最詳細的ReentrantReadWriteLock原始碼剖析(萬字長文)原始碼
- 【Android原始碼】Fragment 原始碼分析Android原始碼Fragment
- 【Android原始碼】Intent 原始碼分析Android原始碼Intent
- k8s client-go原始碼分析 informer原始碼分析(6)-Indexer原始碼分析K8SclientGo原始碼ORMIndex
- k8s client-go原始碼分析 informer原始碼分析(4)-DeltaFIFO原始碼分析K8SclientGo原始碼ORM
- 以太坊原始碼分析(20)core-bloombits原始碼分析原始碼OOM
- 以太坊原始碼分析(24)core-state原始碼分析原始碼
- 以太坊原始碼分析(29)core-vm原始碼分析原始碼
- 【MyBatis原始碼分析】select原始碼分析及小結MyBatis原始碼
- redis原始碼分析(二)、redis原始碼分析之sds字串Redis原始碼字串
- Java併發包原始碼學習系列:ReentrantReadWriteLock讀寫鎖解析Java原始碼
- ArrayList 原始碼分析原始碼
- kubeproxy原始碼分析原始碼