AQS源码分析-04(独占式超时获取锁--tryAcquireNanos(int arg,long timeout))

独占式超时获取锁–tryAcquireNanos(int arg,long timeout)

AQS除了提供上面两个方法外,还提供了一个增强版的方法:tryAcquireNanos(int arg,long nanos)。该方法为acquireInterruptibly方法的进一步增强,它除了响应中断外,还有超时控制。即如果当前线程没有在指定时间内获取同步状态,则会返回false,否则返回true。如下:

public final boolean tryAcquireNanos(int arg, long nanosTimeout)
        throws InterruptedException {
    if (Thread.interrupted())
        throw new InterruptedException();
    return tryAcquire(arg) ||
            doAcquireNanos(arg, nanosTimeout);
}
private boolean doAcquireNanos(int arg, long nanosTimeout)
        throws InterruptedException {
    //如果nanosTimeout小于0直接返回
    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;
            }
            //超时时间点-当前时间=剩余的超时时间
            nanosTimeout = deadline - System.nanoTime();
            //如果剩余的超时时间小于0说明已超时,则返回
            if (nanosTimeout <= 0L)
                return false;
            //如果没有超时则等待nanosTimeout纳秒
            //注:该线程会直接从LockSupport.parkNanos(this, nanosTimeout)中返回
            //LockSupport是JUC提供的一个阻塞和唤醒的工具类
            if (shouldParkAfterFailedAcquire(p, node) &&
                    //如果nanosTimeout大于spinForTimeoutThreshold,就需要休眠nanosTimeout
                    nanosTimeout > spinForTimeoutThreshold)
                LockSupport.parkNanos(this, nanosTimeout);
            //如果nanosTimeout小于等于spinForTimeoutThreshold,那么就不需要休眠了,直接进入快速自旋
            // 因为spinForTimeoutThreshold已经很短了,如果在更短的超时时间内还要休眠,可能会导致超时时间不那么准确
            //线程的状态切换是需要时间的
            
            //判断线程是否已经被中断了
            if (Thread.interrupted())
                throw new InterruptedException();
        }
    } finally {
        if (failed)
            cancelAcquire(node);
    }
}

与独占式获取锁响应中断的不同就在加入到同步队列之后对超时时间的计算

在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

壹氿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值