ReentrantLock可重入独占锁详解

朴灿烈づ我的快乐病毒、 2023-10-12 10:28 117阅读 0赞

基本用法介绍

ReentrantLock位于java.util.concurrent(J.U.C)包下,是Lock接口的实现类。基本用法与synchronized相似,都具备可重入互斥的特性,但拥有更强大的且灵活的锁机制。

ReentrantLock推荐用法如下:

  1. class X {
  2. //定义锁对象
  3. private final ReentrantLock lock = new ReentrantLock();
  4. // ...
  5. //定义需要保证线程安全的方法
  6. public void m() {
  7. //加锁
  8. lock.lock();
  9. try{
  10. // 保证线程安全的代码
  11. }
  12. // 使用finally块保证释放锁
  13. finally {
  14. lock.unlock()
  15. }
  16. }
  17. }

继承体系

c1609af4718a47e430caecf43bdbf5d1.png

  • 实现Lock接口,提供了锁的关键方法,如lock、unlock、tryLock等等,以及newCondition给lock关联条件对象的方法。
  • 内部维护了一个Sync,它继承AQS,实现AQS提供的独占式的获取与释放同步资源的方法,提供了可重入的具体实现。
  • Sync有两个实现类,是公平锁和非公平锁的两种实现,FairSync与NonfairSync。

独占锁表示:同时只能有一个线程可以获取该锁,其他获取该锁的线程会被阻塞而被放入该所的AQS阻塞队列里面。

构造方法

Sync直接继承自AQS,NonfairSync和FairSync继承了Sync,实现了获取锁的公平与非公平策略。

ReentrantLock中的操作都是委托给Sync对象来实际操作的。

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

默认是使用非公平锁:NonfairSync,可以传入参数来指定是否使用公平锁。

  1. // 默认使用的是 非公平的策略
  2. public ReentrantLock() {
  3. sync = new NonfairSync();
  4. }
  5. // 通过fair参数指定 策略
  6. public ReentrantLock(boolean fair) {
  7. sync = fair ? new FairSync() : new NonfairSync();
  8. }

state状态表示

在ReentrantLock中,AQS的state状态值表示线程获取该锁的可重入次数,在默认情况下:

  • state值为0时表示当前锁没有被任何线程持有。
  • 当第一个线程第一次获取该锁时会尝试使用CAS设置state的值为1,如果CAS成功则当前线程获取了该锁,然后记录该锁的持有者为当前线程
  • 在该线程没有释放锁的情况下第二次获取该锁后,状态值设置为2,为可重入次数。
  • 在该线程释放锁时,会尝试使用CAS让state值减1,如果减1后状态值为0,则当前线程释放该锁

获取锁

void lock()方法

ReentrantLock的lock()方法委托给了sync类,根据创建sync的具体实现决定具体的逻辑:

NonfairSync

  1. /**
  2. * Performs lock. Try immediate barge, backing up to normal
  3. * acquire on failure.
  4. */
  5. final void lock() {
  6. // CAS 设置获取state值
  7. if (compareAndSetState(0, 1))
  8. // 将当前线程设置为锁的持有者
  9. setExclusiveOwnerThread(Thread.currentThread());
  10. else
  11. // 设置失败, 调用AQS的acquire方法
  12. acquire(1);
  13. }

state值的初始状态为0,也就是说,第一个线程的CAS操作会成功将0设置为1,表示当前线程获取到了锁,然后通过setExclusiveOwnerThread方法将当前线程设置为锁的持有者。

如果这时,其他线程也试图获取该锁,则CAS失败,走到acquire的逻辑。

  1. // AQS#acquire
  2. public final void acquire(int arg) {
  3. // 调用ReentrantLock重写的tryAcquire方法
  4. if (!tryAcquire(arg) &&
  5. // tryAcquire方法返回false,则把当前线程放入AQS阻塞队列中
  6. acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
  7. selfInterrupt();
  8. }

欸,这个时候我们应该就有感觉了,我们之前在分析AQS的核心方法的时候说到过,AQS是基于模板模式设计的,下面的tryAcquire方法就是留给子类实现的,而NonfairSync中是这样实现的:

  1. //NonfairSync#tryAcquire
  2. protected final boolean tryAcquire(int acquires) {
  3. // 调用
  4. return nonfairTryAcquire(acquires);
  5. }
  6. final boolean nonfairTryAcquire(int acquires) {
  7. final Thread current = Thread.currentThread();
  8. // 获取当前状态值
  9. int c = getState();
  10. // 如果当前状态值为0,如果为0表示当前锁空闲
  11. if (c == 0) {
  12. if (compareAndSetState(0, acquires)) {
  13. setExclusiveOwnerThread(current);
  14. return true;
  15. }
  16. }
  17. // 看看当前的线程是不是锁的持有者
  18. else if (current == getExclusiveOwnerThread()) {
  19. // 如果是的话 将状态设置为 c + acquires
  20. int nextc = c + acquires;
  21. if (nextc < 0) // overflow
  22. throw new Error("Maximum lock count exceeded");
  23. setState(nextc);
  24. return true;
  25. }
  26. return false;
  27. }

还是很好理解的哈,先看看锁的状态值是啥?

  • 如果是0,就CAS尝试获取锁,将状态从0变到1,并且设置锁的持有者为当前线程,和之前的逻辑一样啦。
  • 如果不是0,表示已经被某个线程持有啦,看看持有锁的人是谁呢?如果是自己,那么好办,重入呗,将state变为nextc【原先state + 传入的acquires】,返回true。这里要注意:nextc<0表示可重入次数溢出。
  • 锁已经被别人霸占了,那就返回false咯,等待后续acquireQueued(addWaiter(Node.EXCLUSIVE), arg))方法,被置入AQS阻塞队列中。

这里非公平体现在获取锁的时候,没有查看当前AQS队列中是否有比自己更早请求该锁的线程存在,而是采取了抢夺策略

FairSync

公平锁的tryAcquire实现如下:

  1. //FairSync#tryAcquire
  2. protected final boolean tryAcquire(int acquires) {
  3. final Thread current = Thread.currentThread();
  4. int c = getState();
  5. if (c == 0) {
  6. // 状态值为0的时候,我去看看队列里面在我之前有没有线程在等
  7. if (!hasQueuedPredecessors() &&
  8. compareAndSetState(0, acquires)) {
  9. setExclusiveOwnerThread(current);
  10. return true;
  11. }
  12. }
  13. // 当前锁已经被当前线程持有
  14. else if (current == getExclusiveOwnerThread()) {
  15. int nextc = c + acquires;
  16. if (nextc < 0)
  17. throw new Error("Maximum lock count exceeded");
  18. setState(nextc);
  19. return true;
  20. }
  21. return false;
  22. }

对比一下两种策略,不必说,hasQueuedPredecessors方法一定是实现公平性的核心,我们来瞅瞅:

  1. // 如果当前线程有前驱节点就返回true。
  2. public final boolean hasQueuedPredecessors() {
  3. // The correctness of this depends on head being initialized
  4. // before tail and on head.next being accurate if the current
  5. // thread is first in queue.
  6. Node t = tail; // Read fields in reverse initialization order
  7. Node h = head;
  8. Node s;
  9. return h != t &&
  10. ((s = h.next) == null || s.thread != Thread.currentThread());
  11. }

该方法:如果当前线程有前驱节点就返回true,那么我们想,不是前驱节点的情况有哪些呢?

  1. 队列为空
  2. 队列不为空,但当前线程节点是AQS的第一个节点。

知道这些之后,我们就明白最后那串表达式是什么意思了:队列里面的第一个元素不是当前线程,返回true,说明在你之前还有人排着队呢,你先别抢,先到先得

公平与非公平策略的差异

我们稍微总结一下:

Reentrant类的构造函数接受一个可选的公平性参数fair。这时候就出现两种选择:

  • 公平的(fair == true):保证等待时间最长的线程优先获取锁,其实就是先入队的先得锁,即FIFO。
  • 非公平的(fair == false):此锁不保证任何特定的访问顺序。

公平锁往往体现出的总体吞吐量比非公平锁要低,也就是更慢,因为每次都需要看看队列里面有没有在排队的嘛。锁的公平性并不保证线程调度的公平性,但公平锁能够减少”饥饿”发生的概率。

需要注意的是:不定时的tryLock()方法不支持公平性设置。如果锁可用,即使其他线程等待时间比它长,它也会成功获得锁。

void lockInterruptibly()

该方法与lock方法类似,不同点在于,它能对中断进行相应:当前线程在调用该方法时,如果其他线程调用了当前线程的interrupt()方法,当前线程会抛出InterruptedException异常,然后返回。

  1. // ReentrantLock#lockInterruptibly
  2. public void lockInterruptibly() throws InterruptedException {
  3. sync.acquireInterruptibly(1);
  4. }
  5. // AQS#acquireInterruptibly
  6. public final void acquireInterruptibly(int arg)
  7. throws InterruptedException {
  8. // 如果当前线程被中断,则直接抛出异常
  9. if (Thread.interrupted())
  10. throw new InterruptedException();
  11. // 尝试获取资源
  12. if (!tryAcquire(arg))
  13. // 调用AQS可被中断的方法
  14. doAcquireInterruptibly(arg);
  15. }

boolean tryLock()方法

尝试获取锁,如果当前该锁没有被其他线程持有,则当前线程获取该锁并返回true,否则返回false。

大致逻辑和非公平锁lock方法类似,但该方法会直接返回获取锁的结果,无论true或者false,它不会阻塞。

  1. // ReentrantLock# tryLock
  2. public boolean tryLock() {
  3. return sync.nonfairTryAcquire(1);
  4. }
  5. abstract static class Sync extends AbstractQueuedSynchronizer {
  6. // Sync#nonfairTryAcquire
  7. final boolean nonfairTryAcquire(int acquires) {
  8. final Thread current = Thread.currentThread();
  9. int c = getState();
  10. if (c == 0) {
  11. if (compareAndSetState(0, acquires)) {
  12. setExclusiveOwnerThread(current);
  13. return true;
  14. }
  15. }
  16. else if (current == getExclusiveOwnerThread()) {
  17. int nextc = c + acquires;
  18. if (nextc < 0) // overflow
  19. throw new Error("Maximum lock count exceeded");
  20. setState(nextc);
  21. return true;
  22. }
  23. return false;
  24. }
  25. }
  • tryLock() 实现方法,在实现时,希望能快速的获得是否能够获得到锁,因此即使在设置为 fair = true ( 使用公平锁 ),依然调用 Sync#nonfairTryAcquire(int acquires) 方法。
  • 如果真的希望 tryLock() 还是按照是否公平锁的方式来,可以调用 #tryLock(0, TimeUnit) 方法来实现。

boolean tryLock(long timeout, TimeUnit unit)

  1. // ReentrantLock# tryLock
  2. public boolean tryLock(long timeout, TimeUnit unit)
  3. throws InterruptedException {
  4. return sync.tryAcquireNanos(1, unit.toNanos(timeout));
  5. }
  6. // AQS#tryAcquireNanos
  7. public final boolean tryAcquireNanos(int arg, long nanosTimeout)
  8. throws InterruptedException {
  9. if (Thread.interrupted())
  10. throw new InterruptedException();
  11. return tryAcquire(arg) ||
  12. doAcquireNanos(arg, nanosTimeout);
  13. }

尝试获取锁,如果获取失败会将当前线程挂起指定时间,时间到了之后当前线程被激活,如果还是没有获取到锁,就返回false。

另外,该方法会对中断进行的响应,如果其他线程调用了当前线程的interrupt()方法,响应中断,抛出异常。

释放锁

void unlock()方法

  1. // ReentrantLock#unlock
  2. public void unlock() {
  3. sync.release(1);
  4. }
  5. //AQS# release
  6. public final boolean release(int arg) {
  7. // 子类实现tryRelease
  8. if (tryRelease(arg)) {
  9. Node h = head;
  10. if (h != null && h.waitStatus != 0)
  11. unparkSuccessor(h);
  12. return true;
  13. }
  14. return false;
  15. }
  16. abstract static class Sync extends AbstractQueuedSynchronizer {
  17. // Sync#tryRelease
  18. protected final boolean tryRelease(int releases) {
  19. // 计算解锁后的次数,默认减1
  20. int c = getState() - releases;
  21. // 如果想要解锁的人不是当前的锁持有者,直接抛异常
  22. if (Thread.currentThread() != getExclusiveOwnerThread())
  23. throw new IllegalMonitorStateException();
  24. boolean free = false;
  25. // 可重入次数为0,清空锁持有线程
  26. if (c == 0) {
  27. free = true;
  28. setExclusiveOwnerThread(null);
  29. }
  30. // 可重入次数还没到0,只需要改变一下下state就可
  31. setState(c);
  32. return free;
  33. }
  34. }

尝试释放锁,如果当前线程持有该锁,调用该方法默认会让AQS的state减1。

如果减1之后,state为0,当前线程会释放锁。

如果当前线程不是锁持有者而企图调用该方法,则抛出IllegalMonitorStateException异常。

Condition实现生产者消费者

Condition是用来代替传统Object中的wait()和notify()实现线程间的协作,Condition的await()和signal()用于处理线程间协作更加安全与高效

Condition的使用必须在lock()与unlock()之间使用,且只能通过lock.newCondition()获取,实现原理我们之后会专门进行学习。

  1. public class BlockingQueue {
  2. final Object[] items; // 缓冲数组
  3. final ReentrantLock lock = new ReentrantLock(); // 非公平独占锁
  4. final Condition notFull = lock.newCondition(); // 未满条件
  5. final Condition notEmpty = lock.newCondition(); // 未空条件
  6. private int putIdx; // 添加操作的指针
  7. private int takeIdx; // 获取操作的指针
  8. private int count; // 队列中元素个数
  9. public BlockingQueue(int capacity) {
  10. if(capacity < 0) throw new IllegalArgumentException();
  11. items = new Object[capacity];
  12. }
  13. // 插入
  14. public void put(Object item) throws InterruptedException {
  15. try {
  16. lock.lock(); // 上锁
  17. while (items.length == count) { // 满了
  18. notFull.await(); // 其他插入线程阻塞起来
  19. }
  20. enqueue(item); // 没满就可以入队
  21. } finally {
  22. lock.unlock(); // 不要忘记解锁
  23. }
  24. }
  25. private void enqueue(Object item) {
  26. items[putIdx] = item;
  27. if (++putIdx == items.length) putIdx = 0;
  28. count++;
  29. notEmpty.signal(); // 叫醒获取的线程
  30. }
  31. // 获取
  32. public Object take() throws InterruptedException {
  33. lock.lock();
  34. try {
  35. while (count == 0) {
  36. notEmpty.await();// 阻塞其他获取线程
  37. }
  38. return dequeue();
  39. } finally {
  40. lock.unlock();
  41. }
  42. }
  43. private Object dequeue() {
  44. Object x = items[takeIdx];
  45. items[takeIdx] = null;
  46. if (++takeIdx == items.length) takeIdx = 0;
  47. count--;
  48. notFull.signal(); // 叫醒其他的插入线程
  49. return x;
  50. }
  51. }

其实上面就是ArrayBlockingQueue删减版的部分实现,感兴趣的小伙伴可以看看源码的实现,源码上面针对并发还做了更细节的处理。

总结

API层面的独占锁:ReentrantLock是底层使用AQS实现的可重入的独占锁,区别于synchronized原生语法层面实现锁语义,ReetrantLock通过lock()unlock()两个方法显式地实现互斥锁。

state与可重入:AQS的state为0表示当前锁空闲,大于0表示该锁已经被占用,某一时刻只有一个线程可以获取该锁。可重入性是通过判断持锁线程是不是当前线程,如果是,state+1,释放锁时,state-1,为0时表示彻底释放。

公平与非公平策略:ReentrantLock拥有公平和非公平两种策略,区别在于获取锁的时候是否会去检查阻塞队列中,是否存在当前线程的前驱节点,默认是非公平锁策略。

丰富的锁扩展:提供了响应中断的获取锁方式lockInterruptibly,以及提供了快速响应的tryLock方法,及超时获取等等方法。

condition:TODO一个ReentrantLock对象可以通过newCondition()同时绑定多个Condition对象,对线程的等待、唤醒操作更加详细和灵活,这一点我们之后说到Condition的时候会再回过头说的。

发表评论

表情:
评论列表 (有 0 条评论,117人围观)

还没有评论,来说两句吧...

相关阅读