公平鎖和非公平鎖的區別

公平鎖和非公平鎖的區別java

  • 鎖的公平性是相對於獲取鎖的順序而言的,
  • 若是是一個公平鎖,
    • 那麼鎖的獲取順序就應該符合請求的絕對時間順序,也就是FIFO。
  • 非公平鎖只要CAS設置同步狀態成功,則表示當前線程獲取了鎖,
  • 而公平鎖則不同,差別點有兩個:
    • FairSync.tryAcquire
      • final void lock() {
             acquire(1);
        }

         

      • 非公平鎖在獲取鎖的時候,會先經過CAS進行搶佔,而公平鎖則不會
    • FairSync.tryAcquire
      • protected final boolean tryAcquire(int acquires) {
                    final Thread current = Thread.currentThread();
                    int c = getState();
                    if (c == 0) {
                        if (!hasQueuedPredecessors() &&
                            compareAndSetState(0, acquires)) {
                            setExclusiveOwnerThread(current);
                            return true;
                        }
                    }
                    else if (current == getExclusiveOwnerThread()) {
                        int nextc = c + acquires;
                        if (nextc < 0)
                            throw new Error("Maximum lock count exceeded");
                        setState(nextc);
                        return true;
                    }
                    return false;
                }
            }

         

      • 這個方法與nonfairTryAcquire(int acquires)比較,
      • 不一樣的地方在於:
        • 判斷條件多了hasQueuedPredecessors()方法,
        • 也就是加入了(同步隊列中當前節點是否有前驅節點)的判斷,
          • 若是該方法返回true,則表示有線程比當前線程更早地請求獲取鎖,
          • 所以須要等待前驅線程獲取並釋放鎖以後才能繼續獲取鎖。
相關文章
相關標籤/搜索