美文网首页Java并发和JVM
ReentrantLock及AQS源码

ReentrantLock及AQS源码

作者: Lnstark | 来源:发表于2020-12-06 16:01 被阅读0次

    ReentrantLock是可重入锁,实现原理是AQS(AbstractQueuedSynchronizer),作用类似于Java内置锁synchronized。
    它和synchronized的区别:

    • jdk1.5时,synchronized性能较差,1.6引入偏向锁和轻量级锁时,二者性能差不多
    • ReentrantLock需要手动释放锁
    • ReentrantLock可指定公平还是非公平,synchronized是非公平的。
    • ReentrantLock可响应中断,可指定获取锁的等待时间。

    ReentrantLock有三个内部类,Sync、FairSync和NonfairSync,其中FairSync和NonfairSync分别是公平锁和非公平锁,Sync是这两个锁的父类。ReentrantLock的无参构造方法默认他是一个非公平锁:

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

    有参构造可以指定是公平锁还是非公平锁:

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

    ReentrantLock的加锁方法和解锁方法:

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

    都是调用sync的方法,sync其实就是AQS的实现。先来看看公平锁的加锁实现:

    final void lock() {
        acquire(1);
    }
    

    点进去就是AQS的源码:

        public final void acquire(int arg) {
            if (!tryAcquire(arg) &&
                acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
                selfInterrupt();
        }
    

    大致逻辑就是先尝试获取锁,如果获取到了就直接执行一个线程中断,然后退出,如果没获取到,先把当前线程封装成一个节点,加入到阻塞队列里,然后竞争锁,直到获取到锁才退出(也可能出现异常退出)。我们只要重点关注tryAcquire、addWaiter和acquireQueued三个方法就行。先看tryAcquire:

        protected boolean tryAcquire(int arg) {
            throw new UnsupportedOperationException();
        }
    

    AQS把他交给子类实现了,那就来看看公平锁是怎么实现的:

            protected final boolean tryAcquire(int acquires) {
                final Thread current = Thread.currentThread();
                // 获取状态如果状态为0表示没有线程占有锁,如果不为零则表示线程的重入次数
                int c = getState();
                // 如果没有线程持有锁
                if (c == 0) {
                    // 先判断当前节点前面是否有节点,如果没有的话就用CAS的方式设置state
                    if (!hasQueuedPredecessors() &&
                        compareAndSetState(0, acquires)) {
                        // 如果CAS成功,说明抢到锁了,设置持有锁的线程为当前线程,然后返回true,表示抢到锁了
                        setExclusiveOwnerThread(current);
                        return true;
                    }
                }
                // state != 0,说明锁已经被占有,那就在判断一下持有锁的是不是当前线程
                else if (current == getExclusiveOwnerThread()) {
                    // 如果是当前线程的话,那就把state加上重入次数acquires,返回true。这里是没有线程安全问题的
                    int nextc = c + acquires;
                    if (nextc < 0)
                        throw new Error("Maximum lock count exceeded");
                    setState(nextc);
                    return true;
                }
                // 否则没有拿到锁
                return false;
            }
    

    如果没有拿到锁,就进行入队操作,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自旋入队
            enq(node);
            return node;
        }
    

    看看enq方法:

        private Node enq(final Node node) {
            // 自旋直到入队成功
            for (;;) {
                Node t = tail;
                // 如果tail是空,就意味着头结点是空,这是因为第一个抢到锁的线程直接退出了,没有创建节点
                if (t == null) { // Must initialize
                    if (compareAndSetHead(new Node()))
                        tail = head;
                } else {
                    // 否则进行CAS入队操作
                    node.prev = t;
                    if (compareAndSetTail(t, node)) {
                        t.next = node;
                        return t;
                    }
                }
            }
        }
    

    这就是入队逻辑,入队成功后进行竞争队列方法acquireQueued:

        final boolean acquireQueued(final Node node, int arg) {
            boolean failed = true;
            try {
                boolean interrupted = false;
                // 也是一个自旋,直到抢到锁才退出方法
                for (;;) {
                    final Node p = node.predecessor();
                    // 取当前节点的前置节点,判断是不是head,只有head的next节点可以抢占锁。
                    // 执行tryAcquire方法抢占锁,如果抢到了就返回中断标志
                    if (p == head && tryAcquire(arg)) {
                        setHead(node);
                        p.next = null; // help GC
                        failed = false;
                        return interrupted;
                    }
                    // 移除前面的cancelled节点,如果前一个节点状态是0就置为1(SIGNAL)状态。
                    // 如果前置节点是1的话返回true,否则将找到状态为1的前置节点为止,返回false
                    // 返回true之后执行parkAndCheckInterrupt方法park当前线程
                    if (shouldParkAfterFailedAcquire(p, node) &&
                        parkAndCheckInterrupt())
                        interrupted = true;
                }
            } finally {
                if (failed)
                    cancelAcquire(node);
            }
        }
    

    以上是公平锁加锁的大致逻辑。非公平锁和公平锁的区别在于:在持锁线程释放锁到阻塞队列head的next节点获取锁的过程中,非公平锁的线程是可以直接插队拿到锁的,而公平锁不行,必须排队。
    我们看看非公平锁的lock实现:

            final void lock() {
                // 上来直接CAS加锁,如果加锁失败才进行acquire
                if (compareAndSetState(0, 1))
                    setExclusiveOwnerThread(Thread.currentThread());
                else
                    acquire(1);
            }
    

    tryAcquire实现也有不同:

            protected final boolean tryAcquire(int acquires) {
                return nonfairTryAcquire(acquires);
            }
    
            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;
            }
    

    主要是CAS操作之前没有进行判断当前节点前面是否有节点。
    然后我们看看解锁:

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

    先tryRealease尝试释放锁,释放成功的话叫醒head的后继节点,让后继节点抢占锁,返回true,否则返回false,先看看tryRelease方法:

            protected final boolean tryRelease(int releases) {
                int c = getState() - releases;
                // 如果当前线程不是持有锁的线程,抛出异常。毕竟只有持有了锁才可以释放锁啊。
                if (Thread.currentThread() != getExclusiveOwnerThread())
                    throw new IllegalMonitorStateException();
                boolean free = false;
                // 判断锁释放已经完全释放,如果是则设置独占线程为null
                if (c == 0) {
                    free = true;
                    setExclusiveOwnerThread(null);
                }
                setState(c);
                // 返回是否完全释放锁
                return free;
            }
    

    这是释放锁,再看看唤醒的方法:

          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;
            // 如果head节点的状态是signal的话,置位0,即初始化状态
            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.
             * 如果后继节点是canclled状态,或者是null的话,就从尾节点往前遍历,
             * 直到找到一个不为null也不是head,状态不是cancelled的节点
             */
            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及AQS源码

        本文链接:https://www.haomeiwen.com/subject/qoeowktx.html