ReentrantLock與AQS

ReentrantLock的Sync繼承自AQS

  • Sync實現了nonfairTryAcquire 、tryRelease、isHeldExclusively,
    而TryAcquire和lock留給子類實現
abstract static class Sync extends AbstractQueuedSynchronizer {
    private static final long serialVersionUID = -5179523762034025860L;
    abstract void lock();
    final boolean nonfairTryAcquire(int acquires) {
        final Thread current = Thread.currentThread();
        int c = getState();
        if (c == 0) {//當前可重入數爲0,說明鎖沒有被其他線程獲取
            if (compareAndSetState(0, acquires)) {//cas設置狀態爲重入數
                setExclusiveOwnerThread(current);//將當前線程設置爲獨佔
                return true;
            }
        }
        else if (current == getExclusiveOwnerThread()) {//如果當前線程已經是獨佔的
            int nextc = c + acquires;
            if (nextc < 0) // overflow
                throw new Error("Maximum lock count exceeded");
            setState(nextc);//將重入數更新
            return true;
        }
        return false;
    }
    protected final boolean tryRelease(int releases) {
        int c = getState() - releases;//
        if (Thread.currentThread() != getExclusiveOwnerThread())//當前線程沒有獨佔則無法釋放
            throw new IllegalMonitorStateException();
        boolean free = false;
        if (c == 0) {//如果當前狀態爲0,說明鎖沒有被獲取,設置獨佔線程爲空,返回真
            free = true;
            setExclusiveOwnerThread(null);
        }
        setState(c);//如果重入數還沒有變爲0,就設置新的重入數返回
        return free;
    }
    protected final boolean isHeldExclusively() {
        // 在成爲擁有者之前必須獲取狀態
        //當前線程已經是擁有者就不用再檢查
        return getExclusiveOwnerThread() == Thread.currentThread();
    }
    final ConditionObject newCondition() {
        return new ConditionObject();
    }
    // Methods relayed from outer class
    final Thread getOwner() {
        return getState() == 0 ? null : getExclusiveOwnerThread();
    }
    final int getHoldCount() {
        return isHeldExclusively() ? getState() : 0;
    }
    final boolean isLocked() {
        return getState() != 0;
    }
    /**
     * Reconstitutes the instance from a stream (that is, deserializes it).
     */
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
        s.defaultReadObject();
        setState(0); // reset to unlocked state
    }
}

NonfairSync

static final class NonfairSync extends Sync {
    private static final long serialVersionUID = 7316153563782823691L;

    /**
     * Performs lock.  Try immediate barge, backing up to normal
     * acquire on failure.
     */
    final void lock() {
        if (compareAndSetState(0, 1))
            setExclusiveOwnerThread(Thread.currentThread());
        else
            acquire(1);
    }

    protected final boolean tryAcquire(int acquires) {
        return nonfairTryAcquire(acquires);
    }
}

FairSync

static final class FairSync extends Sync {
   private static final long serialVersionUID = -3000897897090466540L;
   final void lock() {
       acquire(1);
   }
   protected final boolean tryAcquire(int acquires) {
       final Thread current = Thread.currentThread();
       int c = getState();
       if (c == 0) {//當前沒有其他線程競爭
           if (!hasQueuedPredecessors() &&//公平鎖的實現查看當前線程是不是head的下一個節點
           //如果有等待的節點就返回true 沒有等待的節點就返回false,進行下一步設置state
               compareAndSetState(0, acquires)) {
               setExclusiveOwnerThread(current);
               return true;
           }
       }
       //當前沒有競爭,已經獲取到鎖直接設置state這是偏向鎖的實現
       else if (current == getExclusiveOwnerThread()) {
           int nextc = c + acquires;
           if (nextc < 0)
               throw new Error("Maximum lock count exceeded");
           setState(nextc);
           return true;
       }
       return false;
   }
}
  • hasQueuedPredecessors
public final boolean hasQueuedPredecessors() {
    Node t = tail; 
    Node h = head;
    Node s;
    //頭結點等於尾節點返回false說明沒有等待的節點
    //頭結點不等於尾節點,查看頭結點的下一個節點是不是空,
    //如果爲空,說明有等待的節點,不爲空就看這個節點是不是當前節點
    //如果是當前節點就返回false 說明沒有等待的節點
    //如果不等於當前節點就返回true說明有等待的節點
    return h != t &&
        ((s = h.next) == null || s.thread != Thread.currentThread());
}
發佈了91 篇原創文章 · 獲贊 4 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章