聊聊高并发(二十七)解析java.util.concurrent各个组件(九) 理解ReentrantLock可重入锁

这篇讲讲ReentrantLock可重入锁,JUC里提供的可重入锁是基于AQS实现的阻塞式可重入锁。这篇 聊聊高并发(十六)实现一个简单的可重入锁 模拟了可重入锁的实现。可重入锁的特点是:

1. 是互斥锁,基于AQS的互斥模式实现,也就是说同时只有一个线程进入临界区,唤醒下一个线程时也只能释放一个等待线程

2. 可重入,通过设置了一个字段exclusiveOwnerThread来标示当前获得锁的线程。获取锁操作是,如果当前线程是已经获得锁的线程,那么获取操作成功。把当前状态作为获得锁次数的计数器,重入一次就加1,释放一次就减1,直到状态为0

3. 1个可重入锁可以关联多个Condition条件对象来操作多个条件队列。Condition接口提供了显式阻塞/唤醒线程的条件队列操作。这点比内置锁和内置条件队列更具灵活性,1个对象只有1个内置锁和1个内置条件队列。看这篇聊聊高并发(十四)理解Java中的管程,条件队列,Condition以及实现一个阻塞队列


来看看ReentrantLock的代码。 它也提供了Sync类来继承AQS,通过实现tryXXX来扩展功能。

1. nonfairTryAcquire()是非公平的tryAcquire操作,可以无视AQS等待队列,直接通过判断状态来尝试获取锁,并把当前线程设置为获取锁的线程来支持可重入性

2. tryRelease()方法通过修改状态来释放锁,如果状态为0,就把exclusiveOwnerThread设置为空,给之后线程竞争

3. newCondition() 方法每次都创建一个ConditionObject来表示1个条件队列。在之前讲AQS的文章中讲了,从条件队列唤醒后不是立刻获得锁,而是从条件队列进入到了同步队列,还是得竞争锁。而队列锁的数据结构提供了先来先服务的特性,并且降低了锁的争用

abstract static class Sync extends AbstractQueuedSynchronizer {
        private static final long serialVersionUID = -5179523762034025860L;

        /**
         * Performs {@link Lock#lock}. The main reason for subclassing
         * is to allow fast path for nonfair version.
         */
        abstract void lock();

        /**
         * Performs non-fair tryLock.  tryAcquire is
         * implemented in subclasses, but both need nonfair
         * try for trylock method.
         */
        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;
        }

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

        protected final boolean isHeldExclusively() {
            // While we must in general read state before owner,
            // we don't need to do so to check if current thread is owner
            return getExclusiveOwnerThread() == Thread.currentThread();
        }

        final ConditionObject newCondition() {
            return new ConditionObject();
        }

        // Methods relayed from outer class

        final Thread getOwner() {
            return getState() == 0 ? null : getExclusiveOwnerThread();
        }

        final int getHoldCount() {
            return isHeldExclusively() ? getState() : 0;
        }

        final boolean isLocked() {
            return getState() != 0;
        }

        /**
         * Reconstitutes this lock instance from a stream.
         * @param s the stream
         */
        private void readObject(java.io.ObjectInputStream s)
            throws java.io.IOException, ClassNotFoundException {
            s.defaultReadObject();
            setState(0); // reset to unlocked state
        }
    }

同样提供了公平锁和非公平锁的FairSync和NonfairSync实现。和之前的Semaphore中公平性的含义一样,非公平性体现在获取操作时是否等待AQS队列中的先来的线程,而一旦非公平获取锁失败,那么就进入AQS队列等待,AQS队列是FIFO的队列

1. 可以看到非公平锁的lock操作,先用最快路径的方式尝试了一次获得锁,如果获取失败,才用acquire操作调用AQS队列

2. 公平锁的tryAcquire操作在状态为0时要先等待先来的线程都是否后才能获得锁,如果有先来的线程,那么就进入AQS队列。如果当前获得锁的线程是自己,就直接获得锁,把状态加1,体现了可重入

static final class NonfairSync extends Sync {
        private static final long serialVersionUID = 7316153563782823691L;

        /**
         * Performs lock.  Try immediate barge, backing up to normal
         * acquire on failure.
         */
        final void lock() {
            if (compareAndSetState(0, 1))
                setExclusiveOwnerThread(Thread.currentThread());
            else
                acquire(1);
        }

        protected final boolean tryAcquire(int acquires) {
            return nonfairTryAcquire(acquires);
        }
    }

    /**
     * Sync object for fair locks
     */
    static final class FairSync extends Sync {
        private static final long serialVersionUID = -3000897897090466540L;

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

        /**
         * Fair version of tryAcquire.  Don't grant access unless
         * recursive call or no waiters or is first.
         */
        protected final boolean tryAcquire(int acquires) {
            final Thread current = Thread.currentThread();
            int c = getState();
            if (c == 0) {
                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;
        }
    }

默认的ReentrantLock使用的是非公平锁

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

ReentrantLock提供了

1. 可中断和不可中断的lock操作

2. 提供了tryLock()方式非公平的获取一次锁,如果不成功就返回

3. 提供了tryLock(long timeout, TimeUnit unit)的限时锁


public void lock() {
        sync.lock();
    }

 public void lockInterruptibly() throws InterruptedException {
        sync.acquireInterruptibly(1);
    }

public boolean tryLock() {
        return sync.nonfairTryAcquire(1);
    }

public boolean tryLock(long timeout, TimeUnit unit)
            throws InterruptedException {
        return sync.tryAcquireNanos(1, unit.toNanos(timeout));
    }

public Condition newCondition() {
        return sync.newCondition();
    }


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。