AbstractQueuedSynchronizer(二)——acquire/acquireQueued方法

/**
     * Acquires in exclusive mode, ignoring interrupts.  Implemented
     * by invoking at least once {@link #tryAcquire},
     * returning on success.  Otherwise the thread is queued, possibly
     * repeatedly blocking and unblocking, invoking {@link
     * #tryAcquire} until success.  This method can be used
     * to implement method {@link Lock#lock}.
     *
     * @param arg the acquire argument.  This value is conveyed to
     *        {@link #tryAcquire} but is otherwise uninterpreted and
     *        can represent anything you like.
     */
    public final void acquire(int arg) {
        if (!tryAcquire(arg) &&
            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
            selfInterrupt();
    }

一、acquire的三个步骤

先看看当前线程能否获得资源,如果能获得资源,就不用调用acquireQueued了。

1.尝试获取——tryAcquire方法

{@link java.util.concurrent.locks.AbstractQueuedSynchronizer#acquire(int)},
以排它的方式获得锁,对中断不敏感,完成synchronized语义。
1.尝试获取<br/>
{@link java.util.concurrent.locks.AbstractQueuedSynchronizer#tryAcquire(int)}
更改状态
2.{@link java.util.concurrent.locks.AbstractQueuedSynchronizer#tryAcquire(int)}
失败会入队列
{@link java.util.concurrent.locks.AbstractQueuedSynchronizer#acquire(int)}包括了
获取锁失败+入队列操作/成功获取锁操作

<p/>

2.入队列addWaiter

新的节点从队尾插入,用compareAndSetTail保证原子性。node的模式是Node.EXCLUSIVE。.只有没获取到锁的线程才会入队列。

这里有一个fast-path,直接先试一次原子设置tail。

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

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


 

3关于acquire中的acquireQueued方法

自旋获取锁的过程。

判断当前节点的前驱节点。

需要获取当前节点的前驱节点的状态,当前驱节点是头结点并且当前节点(线程)能够获取状态(tryAcquire方法成功),

代表该当前节点占有锁,如果满足上述条件,那么代表能够占有锁,根据节点对锁占有的含义,设置头结点为当前节点(setHead)。

如果没有满足上述条件,调用parkAndCheckInterrupt方法使得当前线程disabled,直到unpark调用,Thread的interrupt调用,然后重新轮训去尝试上述操作。

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);
        }
    }
private final boolean parkAndCheckInterrupt() {
        LockSupport.park(this);
        return Thread.interrupted();
    }

即使前驱节点是头结点,但是tryAcquire方法也未必会成功,对于偏向锁(非公平锁)来说新来一个节点会优先去tryAcquire竞争锁资源,如果成功了,那么这个前驱为头结点的节点进行tryAcquire就会失败。

4.修改前驱节点状态shouldParkAfterFailedAcquire

如果前驱没有被初始化过(值为0),把前驱的状态修改为Node.SIGNAL。

如果前驱节点是CANCELLED(1),跳过该节点,向前找到状态不是CANCELLED的那个节点作为当前节点的前驱。

如果状态是0或者PROPAGATE,原子操作设置node的状态为SIGNAL,但是暂且不park,再重试一次看是否能获得锁。(为什么)

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

5.头结点

头结点在初始化的时候是new出来的,无论何时,头结点的thread和prev属性都是null。

二、关于acquire方法总结

1. 状态的维护;
需要在锁定时,需要维护一个状态(int类型),而对状态的操作是原子和非阻塞的,
通过同步器提供的对状态访问的方法对状态进行操纵,并且利用compareAndSet来确保原子性的修改。
2. 状态的获取;
当前驱节点是头结点,并且成功的修改了状态(tryAcquire方法成功),当前线程或者说节点,就被设置为头节点。
3.修改前驱状态信息
{@link java.util.concurrent.locks.AbstractQueuedSynchronizer#shouldParkAfterFailedAcquire},
如果前驱没有被初始化过(值为0),把前驱的状态修改为Node.SIGNAL。
4. sync队列的维护。
在获取资源未果的过程中条件不符合的情况下(前驱节点不是头节点或者没有获取到资源)进入睡眠状态,
停止线程调度器对当前节点线程的调度,
{@link java.util.concurrent.locks.AbstractQueuedSynchronizer#parkAndCheckInterrupt()}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
AQS的acquireQueued方法是在tryAcquire执行失败后,用于将当前线程加入到等待队列,并在适当的时候阻塞线程。具体流程如下: 1. 首先,使用addWaiter方法将当前线程添加到等待队列中,该方法会创建一个节点并将其插入到等待队列的尾部。 2. 然后,调用shouldParkAfterFailedAcquire方法来判断是否应该阻塞当前线程。该方法会根据前驱节点的等待状态来决定是否需要阻塞当前线程。 - 如果前驱节点的等待状态为Node.SIGNAL,表示前驱节点释放锁之后会唤醒当前节点,此时应该阻塞当前线程。 - 如果前驱节点的等待状态大于0,表示前驱节点取消了等待,需要将当前节点的前驱节点设置为前驱节点的前驱节点,直到找到一个等待状态不大于0的节点为止。然后将当前节点插入到该节点之后。 - 如果前驱节点的等待状态既不是Node.SIGNAL,也不大于0,则使用compareAndSetWaitStatus方法将前驱节点的等待状态设置为Node.SIGNAL,表示当前节点需要被唤醒。 3. 最后,根据shouldParkAfterFailedAcquire方法的返回值来判断是否需要阻塞当前线程。如果shouldParkAfterFailedAcquire方法返回false,表示不需要阻塞当前线程,则acquireQueued方法会一直自旋直到成功获取锁为止。如果shouldParkAfterFailedAcquire方法返回true,表示需要阻塞当前线程,则调用LockSupport.park方法阻塞当前线程,直到被唤醒为止。 <span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [AQS核心流程解析-acquire方法](https://blog.csdn.net/IToBeNo_1/article/details/123404852)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值