为源码写注释: ReentrantLock

本文深入解析ReentrantLock的内部机制,包括成员变量的功能、构造器的区别、lock方法的不同实现等。详细介绍了非公平锁和公平锁的工作原理及其实现细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ReentrantLock:
先简单讲下ReentrantLock里面的成员变量。

(1)int state:用于分辨当前锁是否已经被锁上
1)state=0: 未上锁
2)state>=1:已上锁,并且state>=1时记录的时重入锁的次数

(2)Node head:引用始终指向获得了锁的节点,它不会被取消。acquire操作成功就表示获得了锁,acquire过程中如果中断,那么acquire就失败了,这时候head就会指向下一个节点。

(3)Node tail:尾节点,用于线程快速如队列

1. 构造器

先阐述公平锁和不公平锁的定义

公平锁(Fair):加锁前检查是否有排队等待的线程,优先排队等待的线程,先来先得

非公平锁(Nonfair):加锁时不考虑排队等待问题,直接尝试获取锁,获取不到自动到队尾等待

(1)默认是构造一个不公平的锁。

public ReentrantLock(){
    sync = new NonfairSync();
}

(2)为true时,构造公平锁;为false时,构造不公平锁。

public ReentrantLock(boolean fair){
    sync = fair ? new FairSync() : new NonfairSync();
}

2. lock方法

lock方法针对 fair 和 nonfair 是有不同的实现的,在下面的代码的实现在于 sync 是属于哪个锁

public void lock() {
        sync.lock();
 }

(1)对于NonfairSync.lock() 的实现如下
1) 上锁接口

final void lock() {
        //compareAndSetState,使用cas线程安全的把state的值更改为1, 当state=0时,代表没有上锁
    if (compareAndSetState(0, 1))
            //设置锁的专属对象是当前线程
            setExclusiveOwnerThread(Thread.currentThread());
    else
            //如果cas操作失败时,调用acquire方法尝试上锁
            acquire(1);
}

2) 申请锁

public final void acquire(int arg) {
    // tryAcquire 尝试快速上锁 =>3)
    if (!tryAcquire(arg) &&
        acquireQueued(addWaiter(Node.EXCLUSIVE), arg)) //快速上锁失败后调用acquireQueued方法把当前线程加入队列,并返回acquireQueued中是否产生过拦截
        //acquireQueued中产生拦截,则调用线程中断方法
        selfInterrupt();
}

非公平锁

1)尝试快速上锁

protected final boolean tryAcquire(int acquires) {
    return nonfairTryAcquire(acquires);
}
final boolean nonfairTryAcquire(int acquires) {
    final Thread current = Thread.currentThread();
    int c = getState();
    //state=0时代表未上锁
    if (c == 0) {
        //可上锁时,使用cas操作,线程安全的设置当前锁状态
        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");
        //修改锁状态,不需要cas,因为属于同一个线程
        setState(nextc);
        return true;
    }
    return false;
   }

2) addWaiter: 在当前等待队列添加成员

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;
        // cas线程安全 设置队列尾部等待线程为当前线程
        if (compareAndSetTail(pred, node)) {
            pred.next = node;
            return node;
        }
    }
    //如果尾部节点不存在,则通过死循环插入队列
    enq(node);
    return node;
}

3) 插入当前线程到 锁等待队列上

private Node enq(final Node node) {
    //直到成功才结束
    for (;;) {
        Node t = tail;
        // 尾部节点为空,case线程安全的设置头节点为当前节点,同时设置尾节点。不然,继续在尾部添加node
        if (t == null) { // Must initialize
            if (compareAndSetHead(new Node()))
                tail = head;
        } else {
            node.prev = t;
            if (compareAndSetTail(t, node)) {
                t.next = node;
                return t;
            }
        }
    }
}

4) 在所等待队列中分配锁

final boolean acquireQueued(final Node node, int arg) {
    boolean failed = true;
    try {
        // 是否产生中断
        boolean interrupted = false;
        for (;;) {
            // 获取候锁队列的前一个节点
            final Node p = node.predecessor();
            // 如果node节点的前一个节点p == head,并且tryAcquire为当前线程拿到锁,则分配锁成功
            if (p == head && tryAcquire(arg)) {
                setHead(node);
                p.next = null; // help GC
                failed = false;
                return interrupted;
            }
            // 请求锁失败时,使用shouldParkAfterFailedAcquire判断是否要中断当前线程,需要中断当前线程则调用parkAndCheckInterrupt产生一次中断
        /**线程的thread.interrupt()方法是中断线程,将会设置该线程的中断状态位,即设置为true,中断的结果线程是死亡、还是等待新的任务或是继续运行至下一步,就取决于这个程序本身。线程会不时地检测这个中断标示位,以判断线程是否应该被中断(中断标示值是否为true)。它并不像stop方法那样会中断一个正在运行的线程。*/
            if (shouldParkAfterFailedAcquire(p, node) 
                && parkAndCheckInterrupt())
                interrupted = true;
        }
    } finally {
        //  分配失败,要取消当前线程的锁请求
        if (failed)
            cancelAcquire(node);
    }
}

5) 请求锁失败时,是否中断当前线程,这里首先要了解Node的waitStatus的定义

class:AbstractQueuedSynchronizer.Node

/** waitStatus value to indicate thread has cancelled:当前线程已注销 */
static final int CANCELLED =  1;
/** waitStatus value to indicate successor's thread needs unparking:当前线程的继承者(后继线程)需要唤醒*/
static final int SIGNAL    = -1;
/** waitStatus value to indicate thread is waiting on condition:当前线程在等待Condition唤醒*/
static final int CONDITION = -2;
/**
 * waitStatus value to indicate the next acquireShared should:暂时不看
 * unconditionally propagate
 */
static final int PROPAGATE = -3;

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 {
            /* 前一个线程等待状态为-2或-3,cas线程安全的设置前一个线程的状态为SIGNAL,即当前线程需要唤醒
             * 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;
    }

6) 中断并且检查线程有没有中断

    private final boolean parkAndCheckInterrupt() {
        LockSupport.park(this);
        return Thread.interrupted();
    }

7) 注销线程对锁的请求

    /**
     * Cancels an ongoing attempt to acquire.
     *
     * @param node the node
     */
    private void cancelAcquire(Node node) {
        // Ignore if node doesn't exist
        if (node == null)
            return;

        node.thread = null;
        // 向前回溯,跳过取消的前继节点,直到找到一个没有取消的节点(注意:这里跳过的节点都是无效节点,其实可以从队列中移除),并使当前节点的前继节点指向它,此时找到的那个节点的后继节点没有改动
        // Skip cancelled predecessors
        Node pred = node.prev;
        while (pred.waitStatus > 0)
            node.prev = pred = pred.prev;

        // predNext is the apparent node to unsplice. CASes below will
        // fail if not, in which case, we lost race vs another cancel
        // or signal, so no further action is necessary.
        Node predNext = pred.next;

        // Can use unconditional write instead of CAS here.
        // After this atomic step, other Nodes can skip past us.
        // Before, we are free of interference from other threads.
        //设置当前节点为取消状态
        node.waitStatus = Node.CANCELLED;

        //当前节点就是尾节点,则直接清除尾节点,设置前一个节点的后继节点为null,取消完成
        // If we are the tail, remove ourselves.
        if (node == tail && compareAndSetTail(node, pred)) {
            compareAndSetNext(pred, predNext, null);
        } else {
            // 如果后继节点需要唤醒,先从设置前继节点的指向入手。如果前继节点不是头节点时,因为前继节点之后到当前节点(node)直接的节点都是被跳过了(节点已取消),所以如果pred的waitStatus如果是SIGNAL状态,意味着node的下个节点会唤醒,所以把pred的下个节点设置为node的下个节点,同时也完成了node节点的取消操作。
            // If successor needs signal, try to set pred's next-link
            // so it will get one. Otherwise wake it up to propagate.
            int ws;
            if (pred != head &&
                ((ws = pred.waitStatus) == Node.SIGNAL ||
                 (ws <= 0 && compareAndSetWaitStatus(pred, ws, Node.SIGNAL))) &&
                pred.thread != null) {
                Node next = node.next;
                if (next != null && next.waitStatus <= 0)
                    compareAndSetNext(pred, predNext, next);
            } else {
                //上面尝试没完成后,直接唤醒后继节点
                unparkSuccessor(node);
            }

            node.next = node; // help GC
        }
    }

8). next指向非null的下一个节点,在同步队列中等待的节点,入队操作时设置了前一个节点的next值,这样可以在释放锁时,通知下一个节点来获取锁

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);
}

FairSync:公平锁

(1) 上锁

final void lock() {
    //和非公平锁(NonfairSync)不一样的是,没有快速上锁(抢锁)的机制(compareAndSetState)
    //acquire 和 NonfairSync 一样,都是通过 AbstractQueuedSynchronizer 的acquire 去实现上锁
    //但是对于tryAcquire的实现机制又有不同
    acquire(1);
}

(2)尝试获取锁

protected final boolean tryAcquire(int acquires) {
    final Thread current = Thread.currentThread();
    int c = getState();
    if (c == 0) {
        //和NonfairSync不同的是,多了一个 hasQueuedPredecessors 的判断当前队列是否有等待更久的线程
        if (!hasQueuedPredecessors() &&
            // cas 更改锁状态,返回true 则成功获取锁 
            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;
}

(3)判断当前队列是否有 正在工作的节点 或 等待更久的线程,有就返回true

public final boolean hasQueuedPredecessors() {
    // The correctness of this depends on head being initialized
    // before tail and on head.next being accurate if the current
    // thread is first in queue.
    Node t = tail; // Read fields in reverse initialization order
    Node h = head;
    Node s;
    return h != t &&
        ((s = h.next) == null || s.thread != Thread.currentThread());
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值