歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux編程 >> Linux編程

Lock的實現之ReentrantLock詳解

摘要

Lock在硬件層面依賴CPU指令,完全由Java代碼完成,底層利用LockSupport類和Unsafe類進行操作;

雖然鎖有很多實現,但是都依賴AbstractQueuedSynchronizer類,我們用ReentrantLock進行講解;

ReentrantLock調用過程

ReentrantLock類的API調用都委托給一個內部類 Sync ,而該類繼承了 AbstractQueuedSynchronizer類;

public class ReentrantLock implements Lock, java.io.Serializable {
    ......
    abstract static class Sync extends AbstractQueuedSynchronizer {
......

而Sync又分為兩個子類:公平鎖和非公平鎖,默認為非公平鎖

 /** * Sync object for non-fair locks */ static final class NonfairSync extends Sync { 

 /** * Sync object for fair locks */ static final class FairSync extends Sync { 

Lock的調用過程如下圖(其中涉及到 ReentrantLock類、Sync(抽象類)、AbstractQueuedSynchronizer類,NofairSync類,這些類將 Template方法用的淋漓盡致,相當贊):

先來一張類依賴圖:

再來一張lock調用圖:

Lock API詳解

自底而上來看,由被調用一步步向上分析

nofairTryAcquire

/**
 * Performs non-fair tryLock.  tryAcquire is implemented in
 * subclasses, but both need nonfair try for trylock method.
 */
final boolean nonfairTryAcquire(int acquires) {
    final Thread current = Thread.currentThread();
    int c = getState();
    if (c == 0) {
        if (compareAndSetState(0, acquires)) {
            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;
}

來看這段代碼,首先獲取當前狀態(初始化為0),當它等於0的時候,代表還沒有任何線程獲得該鎖,然後通過CAS(底層是通過CompareAndSwapInt實現)改變state,並且設置當前線程為持有鎖的線程;其他線程會直接返回false;當該線程重入的時候,state已經不等於0,這個時候並不需要CAS,因為該線程已經持有鎖,然後會重新通過setState設置state的值,這裡就實現了一個偏向鎖的功能,即鎖偏向該線程;

addWaiter

只有當鎖被一個線程持有,另外一個線程請求獲得該鎖的時候才會進入這個方法

/**
 * Creates and enqueues node for current thread and given mode.
 *
 * @param mode Node.EXCLUSIVE for exclusive, Node.SHARED for shared
 * @return the new 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)) {
            pred.next = node;
            return node;
        }
    }
    enq(node);
    return node;
}

首先持有該鎖之外的線程進入到該方法,這裡涉及到一個CLH(三個人的名字首字母:Craig, Landin, and Hagersten)隊列,其實就是一個鏈表,

簡單說下CLH隊列:

CLH隊列由node節點組成,mode代表每個Node有兩種模式:共享模式和排他模式,並且維護了一個狀態:waitStatus,可取值如下:

  1. CANCELLED = 1   由於超時或者被打斷,該線程被取消,將不會被block;
  2. SIGNAL = -1    當前線程的後繼節點線程通過park正處於或即將處於block狀態;
  3. CONDITION = -2    當前線程正處於條件隊列,正式因為調用了condition.await造成阻塞;
  4. PROPAGATE = -3    共享鎖應該被傳播出去

首先,new一個節點,這個時候模式為:mode為 Node.EXCLUSIVE,默認為null即排它鎖;

然後:

如果該隊列已經有node即tail!=null,則將新節點的前驅節點置為tail,再通過CAS將tail指向當前節點,前驅節點的後繼節點指向當前節點,然後返回當前節點;

如果隊列為空或者CAS失敗,則通過enq入隊:

/**
 * Inserts node into queue, initializing if necessary. See picture above.
 * @param node the node to insert
 * @return node's predecessor
 */
private Node enq(final Node node) {
    for (;;) {
        Node t = tail;
        if (t == null) { // Must initialize
            if (compareAndSetHead(new Node()))
                tail = head;
        } else {
            node.prev = t;
            if (compareAndSetTail(t, node)) {
                t.next = node;
                return t;
            }
        }
    }
}

進隊的時候,要麼是第一個入隊並且設置head節點並且循環設置tail,要麼是add tail,如果CAS不成功,則會無限循環,直到設置成功,即使高並發的場景,也最終能夠保證設置成功,然後返回包裝好的node節點;

acquireQueued

/**
 * Acquires in exclusive uninterruptible mode for thread already in
 * queue. Used by condition wait methods as well as acquire.
 *
 * @param node the node
 * @param arg the acquire argument
 * @return {@code true} if interrupted while waiting
 */
final boolean acquireQueued(final Node node, int arg) {
    boolean failed = true;
    try {
        boolean interrupted = false;
        for (;;) {
            final Node p = node.predecessor();
            if (p == head && tryAcquire(arg)) {
                setHead(node);
                p.next = null; // help GC
                failed = false;
                return interrupted;
            }
            if (shouldParkAfterFailedAcquire(p, node) &&
                parkAndCheckInterrupt())
                interrupted = true;
        }
    } finally {
        if (failed)
            cancelAcquire(node);
    }
}

該方法的主要作用就是將已經進入虛擬隊列的節點進行阻塞,我們看到,如果當前節點的前驅節點是head並且嘗試獲取鎖的時候成功了,則直接返回,不需要阻塞;

如果前驅節點不是頭節點或者獲取鎖的時候失敗了,則進行判定是否需要阻塞:

/**
 * Checks and updates status for a node that failed to acquire.
 * Returns true if thread should block. This is the main signal
 * control in all acquire loops.  Requires that pred == node.prev.
 *
 * @param pred node's predecessor holding status
 * @param node the node
 * @return {@code true} if thread should block
 */
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;
    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);
    }
    return false;
}

這段代碼對該節點的前驅節點的狀態進行判斷,如果前驅節點已經處於signal狀態,則返回true,表明當前節點可以進入阻塞狀態;

否則,將前驅節點狀態CAS置為signal狀態,然後通過上層的for循環進入parkAndCheckInterrupt代碼塊park:

/**
 * Convenience method to park and then check if interrupted
 *
 * @return {@code true} if interrupted
 */
private final boolean parkAndCheckInterrupt() {
    LockSupport.park(this);
    return Thread.interrupted();
}

這個時候將該線程交給操作系統內核進行阻塞;

總體來講,acquireQueued就是依靠前驅節點的狀態來決定當前線程是否應該處於阻塞狀態,如果前驅節點處於cancel狀態,則丟棄這些節點,重新構建隊列;

Unlock API詳解

流程類似lock api相關類的流程,這裡講主要的代碼,unlock相對的比較簡單

首先 ReentrantLock 調用 Sync的release接口也就是AbstractQueuedSynchronizer的release接口

/**
 * Releases in exclusive mode.  Implemented by unblocking one or
 * more threads if {@link #tryRelease} returns true.
 * This method can be used to implement method {@link Lock#unlock}.
 *
 * @param arg the release argument.  This value is conveyed to
 *        {@link #tryRelease} but is otherwise uninterpreted and
 *        can represent anything you like.
 * @return the value returned from {@link #tryRelease}
 */
public final boolean release(int arg) {
    if (tryRelease(arg)) {
        Node h = head;
        if (h != null && h.waitStatus != 0)
            unparkSuccessor(h);
        return true;
    }
    return false;
}

這個時候會先調用Sync的tryRelease,如果返回true,則釋放鎖成功

protected final boolean tryRelease(int releases) {
    int c = getState() - releases;
    if (Thread.currentThread() != getExclusiveOwnerThread())
        throw new IllegalMonitorStateException();
    boolean free = false;
    if (c == 0) {
        free = true;
        setExclusiveOwnerThread(null);
    }
    setState(c);
    return free;
}

這個接口的作用很簡單,如果不是獲得鎖的線程調用直接拋出異常,否則,如果當前state-releases==0也就是lock已經完全釋放,返回true,清除資源;

這個返回free之後,release拿到head節點,進入以下代碼:

/**
 * Wakes up node's successor, if one exists.
 *
 * @param node the node
 */
private void unparkSuccessor(Node node) {
    /*
     * If status is negative (i.e., possibly needing signal) try
     * to clear in anticipation of signalling.  It is OK if this
     * fails or if status is changed by waiting thread.
     */
    int ws = node.waitStatus;
    if (ws < 0)
        compareAndSetWaitStatus(node, ws, 0);
 
    /*
     * Thread to unpark is held in successor, which is normally
     * just the next node.  But if cancelled or apparently null,
     * traverse backwards from tail to find the actual
     * non-cancelled successor.
     */
    Node s = node.next;
    if (s == null || s.waitStatus > 0) {
        s = null;
        for (Node t = tail; t != null && t != node; t = t.prev)
            if (t.waitStatus <= 0)
                s = t;
    }
    if (s != null)
        LockSupport.unpark(s.thread);
}

這個作用即:當頭結點的狀態小於0,則將頭結點的狀態CAS為0,然後通過鏈表獲取下一個節點,如果下一個節點為null或者不符合要求的狀態,則從隊尾遍歷整個鏈表,直到遍歷到離head節點最近的一個節點並且

等待狀態符合預期,則將頭結點的後繼節點置為該節點;

對剛剛篩出來的符合要求的節點喚醒,也就是該節點獲得 爭奪 鎖的權利;

這就是非公平鎖的特點:在隊列一直等待的線程不一定比後來的線程先獲得鎖,至此,unlock 已經解釋完成;

凌渡冰 目前就職於美團 Do what you like to impact the world.

Copyright © Linux教程網 All Rights Reserved