AQS-ReentrantLock.lock 源码

ReentrantLock lock = new ReentrantLock();
lock.lock(); // 默认为非公平锁
final void lock() {
        acquire(1);
    }
    
    // AbstractQueuedSynchronizer里面的方法
    public final void acquire(int arg) {
        if (!tryAcquire(arg) &&
            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
            selfInterrupt();
    }
 // 1.1 tryAcquire 具体子类实现 ReentrantLock.NonfairSync(非公平锁)
    protected final boolean tryAcquire(int acquires) {
        return nonfairTryAcquire(acquires);
    }
    // 先尝试去获取一次锁。【CHL队列里面可能还有其他线程等待,这里可以体现出非公平性。】
    final boolean nonfairTryAcquire(int acquires) {
       final Thread current = Thread.currentThread();
        int c = getState();
        if (c == 0) { // 若状态刚好为0,则尝试获取锁。
            if (compareAndSetState(0, acquires)) {
                setExclusiveOwnerThread(current);
                return true;
            }
        }
        else if (current == getExclusiveOwnerThread()) { // 若当前线程持有锁,则直接状态值+1
            int nextc = c + acquires; 
            if (nextc < 0) // overflow
                throw new Error("Maximum lock count exceeded");
            setState(nextc);
            return true;
        }
        return false;
    }
	// 1.2 新增一个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)) { // 比较替换的方式将尾节点指向当前新建的节点【可能失败,如果失败走enq(node)】
                pred.next = node; // 上一个尾节点的下个节点指向当前新建的节点
                return node; // 返回当前节点
            }
        }
        enq(node); // 若尾节点为空,即当前队列为空或者上面的CAS替换失败
        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;
                }
            }
        }
    }

在这里插入图片描述

// 1.3 此时已经尝试获取过锁了失败了,并且当前线程锁的节点已经成功放入队尾了。接下来就只能等待休息啦,直到其他线程彻底释放资源后唤醒自己拉。(unpark())
	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; // 若等待过程中被中断,则标记为true
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }
   
   //  static final int CANCELLED =  1; 节点已取消
   //  static final int SIGNAL    = -1;  后续节点在等待当前节点唤醒。后续节点入队后,会将  前置节点状态设置为-1
   // static final int CONDITION = -2; 条件等待【没明白呀??】
   //  static final int PROPAGATE = -3; 共享模式下,前继结点不仅会唤醒其后继结点,同时也可能会唤醒后继的后继结点。
   // 0 为初始状态
    private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
        int ws = pred.waitStatus;
        if (ws == Node.SIGNAL) // 若前置节点状态值=-1 则表示,可以直接阻塞
            /*
             * This node has already set status asking a release
             * to signal it, so it can safely park.
             */
            return true;
        if (ws > 0) { // 若前置状态的值 > 0 ,则表示有取消的节点,依次向前找到最近的一个节点,排在它的后面。
            /*
             * Predecessor was cancelled. Skip over predecessors and
             * indicate retry.
             */
            do {
                node.prev = pred = pred.prev;
            } while (pred.waitStatus > 0);
            pred.next = node;
        } else { // 若状态=0,则将前置节点状态设置为 -1
            /*
             * 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.
             */
             // 将节点状态设置为-1,目的是为了告诉前置节点。拿完好了通知小弟。此处可能失败。有可能前置节点刚释放完信息。
            compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
        }
        return false;
    }
    
    // LockSupport方法阻塞当前线程。
    private final boolean parkAndCheckInterrupt() {
        LockSupport.park(this);
        return Thread.interrupted();
    }
	// 2.1 公平锁 ReentrantLock.FairSync(相对非公平锁,尝试获取锁时增加了hasQueuedPredecessors()
     protected final boolean tryAcquire(int acquires) {
         final Thread current = Thread.currentThread();
         int c = getState();
         if (c == 0) {
         	// hasQueuedPredecessors 为false的时候阐释获取资源
             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;
     }
 }
 
 // 判断该线程是否需要排队(即是否可以尝试获取资源),
 // 返回false的情况(无需排队的情况)。其他情况需要排队
 // 1, h = t -> 头节点=尾节点 队列中只有一个节点 
 // 2, (s = h.next) != null && s.thread = Thread.currentThread() -> 头节点下个节点不为空且头节点下个节点的线程和当前线程相同。
 public final boolean hasQueuedPredecessors() {
        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());
    }
    

总结流程如下:

  1. tryAcquire()先尝试获取锁(直接比较替换或者检查当当前线程是否持有锁),若成功则返回
  2. 若失败,addWaiter()自旋直到将当前线程放入到等待队列的队尾。并比标记独占模式
  3. acquireQueued 自旋找到一个安全点(前置节点的状态=-1)开始等待。直到被唤醒。唤醒后,若前置节点为头节点。且成功获取资源。则将当前节点设置为头节点。

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值