【并发基础】ReentrantLock详解(二)

本文详细剖析了ReentrantLock的工作原理,包括构造方法、lock()、lockInterruptibly()、tryLock()、unlock()等方法的实现细节。通过对比公平同步器和非公平同步器的区别,阐述了它们如何在获取锁时的策略不同。

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

在之前的AQS详解Condition详解ReentrantLock详解(一)中我们分析了同步队列、condition队列和ReentrantLock中的同步器的底层原理,最后我们通过ReentrantLock对外的接口将整个流程串一遍,思路能够更为清晰,以便对Java的并发有进一步的理解。

构造方法

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

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

ReentrantLock默认创建的是非公平同步器,通过重载方法的fair参数可以指定公平策略。

lock()

public void lock() {
    sync.lock();
}
方法详解
//公平同步器
final void lock() {
    acquire(1);
}

//非公平同步器
final void lock() {
    if (compareAndSetState(0, 1))
        setExclusiveOwnerThread(Thread.currentThread());
    else
        acquire(1);
}
  • 公平同步器的lock方法直接调用AQS的acquire(int)方法,即表明ReentrantLock是独占锁,同时表明lock方法不响应中断
  • 非公平同步器直接通过CAS尝试更新AQS的state变量,如果更新成功则表示当前线程获取到锁,否则同样调用acquire(int)方法。

AQS的acquire(int)会调用ReentrantLock的自定义同步器实现的tryAcquire方法,这里我们重点分析该方法,其他的已经在AQS详解中分析过。

//公平同步器
protected final boolean tryAcquire(int acquires) {
    final Thread current = Thread.currentThread();
    int c = getState();
    //0表示锁未被锁定
    if (c == 0) {
        //hasQueuedPredecessors判断当前线程是否是下一个可执行结点
        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;
}

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());
}
//非公平同步器
protected final boolean tryAcquire(int acquires) {
    return nonfairTryAcquire(acquires);
}

//该方法由父类Sync实现
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;
    }

由源码可知,在ReentrantLock中,使用AQS的state变量来判断锁是否被锁定,当state为0时,则表示锁未被锁定;当state不为0时,则表示锁已被某个线程持有,state的数值仅仅表示持有线程重入的次数,不可能有其他线程持有锁,因为ReentrantLock是独占的。

公平同步器和非公平同步器的实现差异仅仅在于是否调用了AQS的hasQueuedPredecessors方法

  • 公平同步器调用hasQueuedPredecessors方法,判断当前线程是否是下一个可执行结点,然后才会使用CAS更新state状态。同时,只有state为0时,更新才能成功。当前线程如果已经持有该锁,则增加state的值,表示重入次数,当释放锁时会逐渐减少state的值,当state的值为0时才表示线程真正释放了锁。

  • 非公平同步器直接使用CAS尝试更新state变量,其他的与公平同步器类似。

余下的就进入到了AQS的流程:

  • 当获取锁成功后,当前进程会进行自我中断,当前状态处于非阻塞状态,因此仅仅是线程的中断标志被修改为true而已;
  • 获取失败后,将当前线程构造为一个结点加入到同步队列的队尾中,自旋尝试获取锁,此时公平锁非公平锁的处理逻辑已经算是相同的了,因为AQS的acquireQueued方法需要判断当前结点的前驱结点是否为头结点,是头结点才会再次调用自定义同步器的tryAcquire方法。

lockInterruptibly()

public void lockInterruptibly() throws InterruptedException {
    sync.acquireInterruptibly(1);
}

该方法响应中断,调用AQS的acquireInterruptibly(int)方法

public final void acquireInterruptibly(int arg) throws InterruptedException {
    if (Thread.interrupted())
        throw new InterruptedException();
    if (!tryAcquire(arg))
        doAcquireInterruptibly(arg);
}

tryAcquire(arg)表明支持公平和非公平策略。doAcquireInterruptibly方法也是自旋尝试获取锁,获取不到则找到某个安全点进行等待,不过其响应中断,会抛出InterruptedException异常。

tryLock()

public boolean tryLock() {
    return sync.nonfairTryAcquire(1);
}

ReentrantLock的tryLock方法调用Sync的nonfairTryAcquire方法,该方法是非公平的,无论初始化时选择何种公平策略。

tryLock(long, TimeUnit)

public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException {
    return sync.tryAcquireNanos(1, unit.toNanos(timeout));
}

该方法调用AQS的tryAcquireNanos方法,支持响应中断和超时时间。
同时,其采用的公平策略,由初始化的fair参数决定。

public final boolean tryAcquireNanos(int arg, long nanosTimeout) throws InterruptedException {
    if (Thread.interrupted())
        throw new InterruptedException();
    return tryAcquire(arg) || doAcquireNanos(arg, nanosTimeout);
}

这里详细分析下doAcquireNanos方法:

private boolean doAcquireNanos(int arg, long nanosTimeout) throws InterruptedException {
    if (nanosTimeout <= 0L)
        return false;
    //计算超时时间点
    final long deadline = System.nanoTime() + nanosTimeout;
    //将当前结点加入同步队列
    final Node node = addWaiter(Node.EXCLUSIVE);
    boolean failed = true;
    try {
        for (;;) {
            final Node p = node.predecessor();
            if (p == head && tryAcquire(arg)) {
                setHead(node);
                p.next = null; // help GC
                failed = false;
                return true;
            }
            //超时则结束自旋,返回false
            nanosTimeout = deadline - System.nanoTime();
            if (nanosTimeout <= 0L)
                return false;
            if (shouldParkAfterFailedAcquire(p, node) &&
                nanosTimeout > spinForTimeoutThreshold)
                LockSupport.parkNanos(this, nanosTimeout);
            if (Thread.interrupted())
                throw new InterruptedException();
        }
    } finally {
        if (failed)
            cancelAcquire(node);
    }
}

unlock()

public void unlock() {
    sync.release(1);
}

ReentrantLock的自定义同步器都未实现release方法,因此这里直接调用父类AQS的方法。

public final boolean release(int arg) {
    if (tryRelease(arg)) {
        Node h = head;
        if (h != null && h.waitStatus != 0)
            unparkSuccessor(h);
        return true;
    }
    return false;
}

ReentrantLock的自定义同步器Sync类实现了tryRelease方法:

protected final boolean tryRelease(int releases) {
    int c = getState() - releases;
    //当前线程未持有该锁,抛出IllegalMonitorStateException异常
    if (Thread.currentThread() != getExclusiveOwnerThread())
        throw new IllegalMonitorStateException();
    boolean free = false;
    //state减为0时,表示当前线程释放该锁
    if (c == 0) {
        free = true;
        setExclusiveOwnerThread(null);
    }
    setState(c);
    return free;
}

当前线程释放锁之后,会唤醒后继结点,头结点的waitStatus为0时表示已经唤醒过后继结点。

AQS的unparkSuccessor方法如下:

private void unparkSuccessor(Node node) {

    int ws = node.waitStatus;
    //将头结点的状态置为0
    if (ws < 0)
        compareAndSetWaitStatus(node, ws, 0);

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

小结

ReentrantLock是独占锁,同一时刻只有一个线程可以获得锁,其具体实现就是让同步队列中的头结点独占资源(将state加1,state代表重入次数),执行完任务后才会释放资源(将state减1),如果释放资源后state减到0则表示释放锁,然后会唤醒头结点的后继结点,后继结点对应的线程就有了获取资源的资格。

在公平锁的策略下,一定是后继结点获得资源;如果是非公平锁策略,其他线程调用lock方法时,会立即去尝试获取资源,获取不成功才会添加到同步队列尾部,非公平策略可以增加吞吐量,但是存在线程饥饿的可能性。

同步队列的数据结构如下图:

在这里插入图片描述

如果此时同步队列的头结点线程调用Condition对象的await方法,会新建结点添加到等待队列的尾部,并且释放掉线程占有的全部资源(将state置为0),同时唤醒后继结点,后继结点会尝试获取资源,如果后继结点获取到资源,则将后继结点设置为新的头结点,意味着旧头结点出队列。

在这里插入图片描述

当同步队列的头节点调用signal方法时(只有获取锁的线程才能调用signal方法,而且signal不释放锁),等待队列的头结点会出队列,并加入到同步队列的尾部,然后按照同步队列的逻辑等待获取锁。sianalAll方法逻辑类似,只是操作对象是整个等待队列的结点。

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值