1. 程式人生 > 其它 >ReentrantLock & AQS

ReentrantLock & AQS

概念

Syncronized由於其使用的不靈活性,逐漸的被拋棄~ 常用解決方案,有以下三種使用方式:(暫時的不考慮condition的應用,暫時還沒有總結出來)

  • 同步普通方法,鎖的是當前物件。
  • 同步靜態方法,鎖的是當前 Class 物件。
  • 同步塊,鎖的是 () 中的物件。

實現原理

JVM 是通過進入、退出物件監視器( Monitor )來實現對方法、同步塊的同步的。

具體實現是在編譯之後在同步方法呼叫前加入一個 monitor.enter 指令,在退出方法和異常處插入 monitor.exit 的指令。

其本質就是對一個物件監視器( Monitor )進行獲取,而這個獲取過程具有排他性從而達到了同一時刻只能一個執行緒訪問的目的。

而對於沒有獲取到鎖的執行緒將會阻塞到方法入口處,直到獲取鎖的執行緒 monitor.exit 之後才能嘗試繼續獲取鎖。

ReentrantLock 是一個可重入的排他鎖。其主要的方法有 lock tryLock unlock。
主要講公平鎖的lock方法。ReentrantLock的lock方法藉助了FairSync的lock方法,先放類圖,有個簡單的瞭解
是一個重入鎖:一個執行緒獲得了鎖之後仍然可以反覆的加鎖,不會出現自己阻塞自己的情況。

程式碼演示

final void lock() {
acquire(1); //定義成final型別,不允許被重寫 lock是個同步阻塞的方法,會堵塞到獲取鎖成功
 }
 public final void acquire(int arg) {
 if (!tryAcquire(arg) && //收先嚐試去獲取鎖
 acquireQueued(addWaiter(Node.EXCLUSIVE), arg)) //獲取不到鎖的話把自身封裝成一個一個node放入到等待的佇列中去
 selfInterrupt();
 }
     //關於佇列的形狀,jdk還畫了個圖,可以簡單的對照
 * +------+ prev +-----+ +-----+
 * head | | <---- | | <---- | | tail
 * +------+ +-----+ +-----+
 protected final boolean tryAcquire(int acquires) {
 final Thread current = Thread.currentThread();
 int c = getState(); //判斷aqs的同步狀態 為0 說明 現在aqs沒有被任何的執行緒所佔有
 if (c == 0) {
 if (!hasQueuedPredecessors() && //判斷當前節點是否是頭結點 或者當前佇列為空(因為是公平鎖,當然是在最前面的才可以執行)
 compareAndSetState(0, acquires)) { //使用cas將aqs的status增加 表明執行緒重入的次數
 setExclusiveOwnerThread(current); //設定當前的執行緒為 執行執行緒
 return true; //成功的搶到鎖了,可以happy的返回,並執行同步語句了
 }
 }
 else if (current == getExclusiveOwnerThread()) { //繼續判斷搶鎖的執行緒是否是執行執行緒 與上同義不再講解
 int nextc = c + acquires; 
 if (nextc < 0)
 throw new Error("Maximum lock count exceeded");
setState(nextc);
 return true;
 }
 return false;
 }

//如果上面的方法執行失敗,要麼是有執行緒已經持有了鎖還沒釋放,或者是還有其他的執行緒在此執行緒之前在隊裡面排隊,於是此執行緒將自己封裝成一個node也加入到佇列裡面去
private Node addWaiter(Node mode) {
Node node = new Node(Thread.currentThread(), mode);
 // Try the fast path of enq; backup to full enq on failure
 Node pred = tail;
 if (pred != null) {
node.prev = pred;
 if (compareAndSetTail(pred, node)) { //進行一次cas將自己插入到tail後面,如果失敗,那麼走enq
 pred.next = node;
 return node;
 }
 }
enq(node);
 return node;
 }
 private Node enq(final Node node) {
 for (;;) {
Node t = tail;
 if (t == null) { // Must initialize
 if (compareAndSetHead(new Node())) //其實就是使用一個死迴圈直到cas成功的將node加入到tail位置,這是個樂觀鎖的設計,但是不堵塞別的執行緒
 tail = head;
 } else {
node.prev = t;
 if (compareAndSetTail(t, node)) {
t.next = node;
 return t;
 }
 }
 }
 }

插入成功之後,此node會繼續的掙扎一下,看是否可以取得aqs的鎖,如下:

final boolean acquireQueued(final Node node, int arg) {
 boolean failed = true;
 try {
 boolean interrupted = false;
 for (;;) {
 final Node p = node.predecessor(); //如果當前執行緒的前任執行緒是head,那麼繼續的嘗試去獲得鎖,就是前面的介紹
 if (p == head && tryAcquire(arg)) {
setHead(node);
p.next = null; // help GC
 failed = false;
 return interrupted;
 }
 if (shouldParkAfterFailedAcquire(p, node) && //如果失敗,那麼繼續的判斷是否將自己park,免得一直的for浪費時間
 parkAndCheckInterrupt())
interrupted = true;
 }
 } finally {
 if (failed)
cancelAcquire(node);
 }
 }
private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
 int ws = pred.waitStatus;
 if (ws == Node.SIGNAL)
 /*
* This node has already set status asking a release
* to signal it, so it can safely park. 
*/
 return true; //前任節點都在乖乖的park了,自己也park吧
 if (ws > 0) {
 /*
* Predecessor was cancelled. Skip over predecessors and
* indicate retry.
*/
 do {
node.prev = pred = pred.prev; //前任節點死了,那麼繼續的去嘗試
 } while (pred.waitStatus > 0);
pred.next = node;
 } else {
 /*
* waitStatus must be 0 or PROPAGATE. Indicate that we
* need a signal, but don't park yet. Caller will need to
* retry to make sure it cannot acquire before parking.
*/
compareAndSetWaitStatus(pred, ws, Node.SIGNAL); //cas嘗試將ws設定為signal
 }
 return false;
 }

等於說如上的方法要麼獲得鎖要麼把自己park起來,等待被喚醒那什麼時候會被喚醒呢,當然是執行緒執行unlock的時候了

public void unlock() {
sync.release(1); //仍然是呼叫同步器來釋放鎖
 }

public final boolean release(int arg) {
 if (tryRelease(arg)) { //釋放鎖,將aqs的state減少
 Node h = head;
 if (h != null && h.waitStatus != 0) //h的status等於0說明這個已經獲得了鎖在執行的過程中,不用打擾,減一,退出就可以,這用在同一個執行緒重入的情況下
 unparkSuccessor(h); //不然的話準備的喚醒
 return true;
 }
 return false;
 }