ReenTrantLock源码解析

可重入锁在实现上基于AQS框架,内部维护线程的state以及队列(CLH)的waitStatus,大量采用非阻塞算法,在中低量的并发上效率是非常高的。

下面分多种情况分析源码,这里只分析非公平锁。

1.简单应用,不使用条件队列

  final ReentrantLock lock=new ReentrantLock();
        for (int i = 0; i <2; i++) {
            final int task=i;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    lock.lock();
                    try{
                        System.out.println(Thread.currentThread().getName()+" is task "+task);
                    }finally {
                        lock.unlock();
                    }
                }
            }).start();
        }

->加锁

        final void lock() {
            if (compareAndSetState(0, 1))
                setExclusiveOwnerThread(Thread.currentThread());
            else
                acquire(1);
        }

这里采用cas并发原语,只有一个线程可以将state状态设置为1,然后设置排他线程,后续的线程都会进入acquire的CLH的队列中。

 public final void acquire(int arg) {
        if (!tryAcquire(arg) &&
            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
            selfInterrupt();
    }
        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;
        }

1.acquire调用tryAcquire接口,最终调用的是nonfairTryAcquire。这里重复了之前的操作,考虑到大量并发的情况下,会出现未进入队列的线程和已进入队列的线程产生竞争,重新检测条件可以避免这种情况,这里是公平锁与非公平锁的主要区别。else if里面的代码就是可重入的意思,如果当前线程二次进入加锁状态,这里会增加计数,并将线程的状态设置为计数值;其它的情况统统返回false,然后进入等待队列中。

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

 

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

2.设置等待队列同样存在大量并发的情况,先是调用addWaiter()将该节点加入队尾并返回当前节点,接着采用自旋操作。if (p == head && tryAcquire(arg)) ,从head节点开始,再次获取条件tryAcquire,如果当前线程没有释放锁,这个条件显然进不去。再来看看 if (shouldParkAfterFailedAcquire(p, node) && parkAndCheckInterrupt())这个判断,前者设置其waitStatus状态,如果线程没有取消,最终的等待状态为-1,最后调用LockSupport阻塞库阻塞线程。

->unlock

 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;
    }
 protected final boolean tryRelease(int releases) {
            int c = getState() - releases;
            if (Thread.currentThread() != getExclusiveOwnerThread())
                throw new IllegalMonitorStateException();
            boolean free = false;
            if (c == 0) {
                free = true;
                setExclusiveOwnerThread(null);
            }
            setState(c);
            return free;
        }

重入是一个一个的进入的,显然释放也要一个一个的释放,release(1)。

if (c == 0) {
                free = true;
                setExclusiveOwnerThread(null);
 }

只有当线程的持有锁的计数变为0时,线程才释放锁。接着是唤醒等待队列,同样是从head节点开始,节点不为null并且其等待状态不为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);

同样,这段代码并不是再同步中完成的,可能会出现已经取消但没有从队列中清除的现象。如果出现这种情况,循环找到该节点后续的第一个等待被唤醒的节点,唤醒对应的等待线程。

2.使用条件队列

测试代码:第一个线程会在加锁后进入警戒条件中,接着线程进入条件队列并释放锁,等待被唤醒;第二个线程起到唤醒的作用。

注:这两个线程并没有存在偏序关系,但是我在测试的时候可以指定线程的触发和运行状态,使其顺序触发或者按特定的顺序触发。

        final ReentrantLock lock=new ReentrantLock();
        Condition condition=lock.newCondition();
        for (int i = 0; i <1 ; i++) {
            final int task=i;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    lock.lock();
                    try{
                        while(state==0){
                            condition.await();
                        }
                        System.out.println(Thread.currentThread().getName()+" is "+task);
                    }catch (java.lang.InterruptedException e){
                        e.printStackTrace();
                    }finally {
                        lock.unlock();
                    }
                }
            }).start();
        }
        Thread.sleep(3000);
        new Thread(new Runnable() {
            @Override
            public void run() {
                lock.lock();
                try{
                    System.out.println(Thread.currentThread().getName()+" is noticing");
                    state=1;
                    condition.signalAll();
                }finally {
                    lock.unlock();
                }
            }
        }).start();

->lock

这个同上

->await

  public final void await() throws InterruptedException {
            if (Thread.interrupted())
                throw new InterruptedException();
            Node node = addConditionWaiter();
            int savedState = fullyRelease(node);
            int interruptMode = 0;
            while (!isOnSyncQueue(node)) {
                LockSupport.park(this);
                if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
                    break;
            }
            if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
                interruptMode = REINTERRUPT;
            if (node.nextWaiter != null) // clean up if cancelled
                unlinkCancelledWaiters();
            if (interruptMode != 0)
                reportInterruptAfterWait(interruptMode);
        }
 private Node addConditionWaiter() {
            Node t = lastWaiter;
            // If lastWaiter is cancelled, clean out.
            if (t != null && t.waitStatus != Node.CONDITION) {
                unlinkCancelledWaiters();
                t = lastWaiter;
            }
            Node node = new Node(Thread.currentThread(), Node.CONDITION);
            if (t == null)
                firstWaiter = node;
            else
                t.nextWaiter = node;
            lastWaiter = node;
            return node;
        }

1.首先检测线程是否中断,接着添加一个等待者到等待队列的队尾,这段代码并没有使用任何同步,在高并发的环境下,可能会报错,所以await方法一定要在同步块中。

    final int fullyRelease(Node node) {
        boolean failed = true;
        try {
            int savedState = getState();
            if (release(savedState)) {
                failed = false;
                return savedState;
            } else {
                throw new IllegalMonitorStateException();
            }
        } finally {
            if (failed)
                node.waitStatus = Node.CANCELLED;
        }
    }

2.这里释放全部的锁,调用release方法,将持有线程设置为null,唤醒head阻塞节点的线程。

   final boolean isOnSyncQueue(Node node) {
        if (node.waitStatus == Node.CONDITION || node.prev == null)
            return false;
        if (node.next != null) // If has successor, it must be on queue
            return true;
        /*
         * node.prev can be non-null, but not yet on queue because
         * the CAS to place it on queue can fail. So we have to
         * traverse from tail to make sure it actually made it.  It
         * will always be near the tail in calls to this method, and
         * unless the CAS failed (which is unlikely), it will be
         * there, so we hardly ever traverse much.
         */
        return findNodeFromTail(node);
    }

3.这里可以存在多种并发情况,跟等待队列有关的是signalAllfang方法,这里会将等待队列中的线程加入阻塞队列。例如下面这段代码:

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

设置一个节点时首先会设置这个节点的prev节点,接着使用cas添加队尾节点,如果失败,if (node.waitStatus == Node.CONDITION || node.prev == null)不满足,节点不在阻塞队列中,所以必须再遍历一遍节点。

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

如果isOnSyncQueue返回false,线程进入阻塞状态;如果这里返回true,表示该线程已经存在阻塞队列中。之前释放了几个锁,这里就获取几个锁acquireQueued(node, savedState)。

3.1.先讨论返回为false的情况,线程进入阻塞后,线程本身无法唤醒自己,只有等待被其它线程唤醒,这种情况下,该线程先检测是否为head节点,然后尝试获取锁,如果这里获取成功,循环退出,然后继续执行

   if (node.nextWaiter != null)
                unlinkCancelledWaiters();

这块代码是在枷锁之后的,目的为了清除之前取消的线程,帮助垃圾回收。

  if (interruptMode != 0)
                reportInterruptAfterWait(interruptMode);

线程的中断状态有三种,0=正常,1=再次中断,-1中断异常。为1时,再次设置线程的中断状态;为-1时,抛出异常。

3.2.如果这里返回true,表示已经被唤醒过并写入同步队列中,接下来尝试获取锁,剩下的操作与上面一样。

3.接下来分析下中断策略

 

 

你可能感兴趣的:(多线程)