ReentrantLock详解

本文导航:

  • 获取锁
  • 释放锁
  • 公平锁与非公平锁
  • ReentrantLock 与 synchronized 的区别
  • 参考资料

ReentrantLock,JUC提供的可重入锁,是一种递归无阻塞的同步机制。
它可以等同于 synchronized 的使用,但是提供了比 synchronized 更强大、更灵活的锁机制。可以减少死锁发生的概率。

API介绍如下(ReentrantLock类注释):

一个可重入的互斥锁,具有与使用 synchronized 方法和语句所访问的隐式监视器锁定相同的基本行为和语义,但是拥有更多的扩展功能。
ReentrantLock 将由最近成功获得锁的,并且还诶有释放该锁的线程所拥有。当该锁没有被另一个线程拥有时,调用lock的线程将成功获取该锁定并返回。当前线程有用该锁时,调用lock方法将会立即返回。
可以使用 isHeloByCurrentThread() 和 getHoldCount() 来进行线程检查



Reentrant还提供了 公平锁非公平锁
构造方法支持一个可选参数,表示创建的锁是否是公平锁。(默认的无参构造器是非公平锁)
这两者的区别在于,公平锁的的获取是有序的。但是公平锁的效率往往要比非公平锁低。在多线程的情况下,公平锁的吞吐量较低。

类的结构关系:

ReentrantLock内部结构

 

锁的初始化

ReentrantLock的大部分逻辑是靠内部类Sync来实现的。
在初始化时,会设置当前锁的类型。
源码如下:

    /** Synchronizer providing all implementation mechanics */
    private final Sync sync;

    public ReentrantLock() {
        sync = new NonfairSync();  // 默认是非公平锁
    }

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

 

获取锁

我们一般使用ReentrantLock时,是这这样获取锁的:

// 非公平锁
ReentrantLock myLock = new ReentrantLock();
myLock.lock();

在源码层面,其实还是调用了内部类Sync 或者 AQS的方法,这个在下面会讲到。

ReentrantLock获取锁的几种方式

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

 

获取锁的方法介绍

lock()
最简单的获取锁方式,尝试获取锁。
1)如果当前锁没有被其他线程持有,则当前线程会立即获取锁并返回,并且设置lock count 为1。
2)如果当前线程已经持有该锁,那么会激励返回,并且 lock count +1。
3)如果锁被其他线程持有,则当前线程在线程调度的状态会变成不可用,然后会被设置为休眠状态,直到线程获取到锁,在获取锁的同时 lock count 置为1。

lockInterruptibly() throws InterruptedException
整体逻辑和lock() 一样,但是该锁是可以被打断的,被打断后,会抛出 InterruptedException。

tryLock()
非阻塞的获取锁。
只有在当前锁没有被其他线程持有的时候,才会获取锁并且马上返回true。
否则会返回false。
源码可以看到,该方法的底层是直接调用的nonfairTryAcquire(1)。
所以说,不管当前重入锁声明的是什么策略,都不会影响该方法的行为。
PS:如果想使用公平锁的策略,并且使用非阻塞的tryLock(),那么可以使用下面的带有过期时间的 tryLock();

tryLock(long timeout, TimeUnit unit) throws InterruptedException
有过期时间的 tryLock()。
在指定时间之内没有获取到锁的话,就会返回false。
在这个时间内获取锁的策略,是支持公平和非公平的。
【需要注意的是】:如果使用的是公平锁的策略,那么即使该锁当前是可用的,也会在队列后面排队。(也就是公平锁策略,排队等待,而不是抢占式)


 

 

释放锁只有一个方法:unlock(),方法实现也是调用了Sync内部类提供的方法。
每次调用该方法 lock count 都会减1,如果count减到0,则锁会释放。

源码如下:

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

 

内部类Sync

这是ReentrantLock 实现锁的关键,所有锁的原理基本都在这个内部类以及AQS中。

Sync是ReentrantLock的一个内部类,它继承AQS(AbstractQueuedSynchronizer),它有两个子类,分别实现了公平锁和费公平锁:FairSync 和 NonfairSync。

以下是源码:
静态内部类Sync

    abstract static class Sync extends AbstractQueuedSynchronizer {
        /**
         * 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();    // 获取当前AQS的线程状态
            if (c == 0) {          // 如果状态为0,即当前没有线程拿到锁。
                // 那么就尝试使用CAS来抢占锁。
                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 the instance from a stream (that is, deserializes it).
         */
        private void readObject(java.io.ObjectInputStream s)
            throws java.io.IOException, ClassNotFoundException {
            s.defaultReadObject();
            setState(0); // reset to unlocked state
        }
    }

可以看到
1)Sync 提供了抽象方法 lock(),具体的实现交给了两个子类来实现。
2)提供了锁释放的实现 tryRelease(int releases) 并且只能由锁的持有者调用,否则会抛出IllegalMonitorStateException()。当lock count 减到0时,释放锁,也就是设置线程的排他Owner为null。
3)Sync提供了非公平锁的tryAcquire实现:nonfairTryAcquire()。
这个方法的主要逻辑:
1、首先获取当前线程current 和 当前锁的状态 c
2、如果锁状态为0,则尝试使用CAS来抢占锁,如果抢占成功,则调用AOS的 setExclusiveOwnerThread(current) 设置当前线程为排他owner,并且返回true。
3、否则走重入逻辑,判断当前线程 current 是否是当前排他锁的owner,如果是,则 lock count+1。返回true。否则返回false。

静态内部类 NonFairSync 和 FairSync

    // 非公平锁静态内部类
    static final class NonfairSync extends Sync {
        /**
         * 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);
        }
    }


    // 公平锁静态内部类
    static final class FairSync extends Sync {
        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;
        }
    }

 

公平锁和非公平锁的区别
可以看到,NonfairSync 和 FairSync 都实现了 lock() 方法。
1)lock()方法的实现。
非公平锁,lock()会直接调用CAS来尝试获取锁,如果获取到了,则直接设置排他Owner为当前线程。否则,就调用acquire(1)。
公平锁,就是直接调用aquire(1)。

2)tryAcquire(int acquires) 的实现
上面可以看到,两个方法都是调用了 acquire(1),这是AQS提供的方法。

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

具体的acquire()方法,这里就不细讲了,到AQS再研究。
这里只需要知道,acquire()是AQS的方法,在AQS内部的acquire方法中,调用的是 tryAcquire(int arg),这个tryAcquire是需要由子类实现。

这里可以看到
NonfairSync的 tryAcquire() 调用的还是 Sync的非公平获取。
FairSync 自己实现了公平的方式的 tryAcquire()。但其实通过代码可以发现,公平锁的 tryAcquire()对比Sync的 nonfairTryAcquire() 几乎一模一样,只是多了一个判断条件:!hasQueuedPredecessors(),加了个非号,也就是判断当前线程是否在CLH同步队列的第一个,如果是则往下走CAS获取锁,否则走重入逻辑。

该方法也是AQS提供的方法,源码如下:

// return TRUE if there is a queued thread preceding the current thread
// return FALSE if the current thread is at the head of the queue or the queue is empty
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());
}

 

ReentrantLock 和 synchronized 的区别

前面提到了,ReentrantLock 提供了比 synchronzed 更加灵活和强大的锁机制,那么强大和灵活如何体现,这两者的区别呢?

首先,从API介绍中可以看到:ReentrantLock是一个可重入的互斥锁,具有与使用 synchronized 方法和语句所访问的隐式监视器锁定相同的基本行为和语义

1)与synchronized相比,ReentrantLock提供了获取锁的扩展功能,例如可中断的锁,快速失败的非等待锁,以及制定时间的锁。
2)ReentrantLock提供了条件Condition,对线程的等待、唤醒操作更加详细和灵活,在多条件变量和高度竞争的环境下,ReentrantLock提供了更高的性能。(Condition相关放在后续整理)
3)ReentrantLock提供了可轮询的锁请求,它会尝试去获取锁,成功则继续,失败则等待下次继续处理。而synchronized一旦进入锁请求要么成功要么阻塞,更容易行成死锁。
4)ReentrantLock支持更加灵活的同步代码块,synchronized只能在同一个结构快中处理。此处注意:ReentrantLock的锁释放一定要在finally中处理,否则很可能产生严重的后果。
5)ReentrantLock支持中断处理,由于内部使用了很多CAS无锁操作,所以性能较好。
6)ReentrantLock的锁和获取需要代码显示的声明和执行,synchronized则是JVM保证了每一个monitorenter都对应一个monitorexit。

 

posted @ 2020-06-03 10:24  47号Gamer丶  阅读(130)  评论(0编辑  收藏  举报