关于java:JDK成长记20-ReenranctLock3释放锁的AQS底层原理

9次阅读

共计 4423 个字符,预计需要花费 12 分钟才能阅读完成。

前两节你应该把握了 ReentrantLock 加锁胜利和加锁失败入队的外围逻辑,是如何通过 AQS 中的 3 个组件做到的。明天来咱们看下:

ReentrantLock 中,当线程开释锁时的逻辑

开释锁的过程及源码分析

<div class=”output_wrapper” id=”output_wrapper_id” style=”width:fit-content;font-size: 16px; color: rgb(62, 62, 62); line-height: 1.6; word-spacing: 0px; letter-spacing: 0px; font-family: ‘Helvetica Neue’, Helvetica, ‘Hiragino Sans GB’, ‘Microsoft YaHei’, Arial, sans-serif;”><h3 id=”hdddd” style=”width:fit-content;line-height: inherit; margin: 1.5em 0px; font-weight: bold; font-size: 1.3em; margin-bottom: 2em; margin-right: 5px; padding: 8px 15px; letter-spacing: 2px; background-image: linear-gradient(to right bottom, rgb(43,48,70), rgb(43,48,70)); background-color: rgb(63, 81, 181); color: rgb(255, 255, 255); border-left: 10px solid rgb(255,204,0); border-radius: 5px; text-shadow: rgb(102, 102, 102) 1px 1px 1px; box-shadow: rgb(102, 102, 102) 1px 1px 2px;”><span style=”font-size: inherit; color: inherit; line-height: inherit; margin: 0px; padding: 0px;”> 开释锁的过程及源码分析 </span></h3></div>

目前通过线程 1、线程 2 应用 ReentrantLock.lock() 后的后果如下:

线程 2 入队期待,线程 1 持有锁,state=1,owner 是线程 1,队列中元素是线程 2,队列是由 Node 节点组成的双向链表,头结点为空,队列具体情况如下:

此时假如线程 1 调用了 unlock() 办法,进行开释锁,会做哪些事件呢?

首先咱们来看一下开释的代码:

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

非常简单,还是应用 Sync 组件(AQS)来开释锁。release() 办法

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

外围分为了 2 步:

1) tryRelease 办法,开释 state 和 owner 变量

2) unparkSuccessor 办法,唤醒队列元素

别离来看一下,首先开释变量 tryRelease 办法:

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

这个办法逻辑很清晰,以后线程是线程 1,state=1,入参 releases 是 1,示意开释一次锁。很显著,state 减 1 后变为 0,会将 owner 也置为空,示意以后没有线程持有锁了,之后设置 state 为 0 完结。

整个过程如下图所示:

批改了 owner 和 state 两个组件的值后,第二步就是唤醒队列期待的线程了。

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

首先开释胜利锁后,应用了 h 指针指向了以后队列的头部,判断一下队列中是否有期待的元素,留神对头元素 waitStatus 不能是 0,如果是 0,阐明队列只有一个空节点,队列中没有期待元素。因为入队元素后会将头结点的 waitStatus 改成 -1,SIGNAL。

接着进入了 unpartSuccessor 办法。从名字看就是复原在 h 节点之后挂起的线程。(PS:JDK 源码外面总会呈现一些语义相近的词语,比方 first-last,head-tail,successor- predecessor,prev-next,其实都是示意前后的意思,是等价的,这点大家要分明。)

private void unparkSuccessor(Node node) {
  int ws = node.waitStatus;
  if (ws < 0)
    compareAndSetWaitStatus(node, ws, 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);
}

node 就是入参 h,head 节点,首先把 head 节点 waitStatus 从 - 1 改为 0。

接着 s =node.next 示意的就是线程 2 排队的 Node,s 不为空,执行了 LockSupport.unpark(s.thread); 将线程 2 进行了唤醒。

最初整个办法返回,release 返回 true 示意开释锁胜利。如下图所示:

此时之前被挂起的线程 2,还记得吗?就是线程 2 已经执行了 LockSupport.park(t) 的操作,线程被挂起,代码会 hang 在那一行期待。

private final boolean parkAndCheckInterrupt() {LockSupport.park(this);
  return Thread.interrupted();}

线程 2 就会接着执行,只有线程 2 没被打断过,返回的必定是 false,以下的 if 条件不会成立。

 if (shouldParkAfterFailedAcquire(p, node) &&parkAndCheckInterrupt())

接着回到 for 循环,从新进行 tryAcquire 操作,线程 2 再次尝试获取锁,此时假如没有别的线程过去加锁。线程 2 天然就会获取锁,设置 state=1,owner= 线程 2 了。

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

下面整个开释锁的过程能够总结如下图:

思考 & 长图总结 ReentrantLock

<div class=”output_wrapper” id=”output_wrapper_id” style=”width:fit-content;font-size: 16px; color: rgb(62, 62, 62); line-height: 1.6; word-spacing: 0px; letter-spacing: 0px; font-family: ‘Helvetica Neue’, Helvetica, ‘Hiragino Sans GB’, ‘Microsoft YaHei’, Arial, sans-serif;”><h3 id=”hdddd” style=”width:fit-content;line-height: inherit; margin: 1.5em 0px; font-weight: bold; font-size: 1.3em; margin-bottom: 2em; margin-right: 5px; padding: 8px 15px; letter-spacing: 2px; background-image: linear-gradient(to right bottom, rgb(43,48,70), rgb(43,48,70)); background-color: rgb(63, 81, 181); color: rgb(255, 255, 255); border-left: 10px solid rgb(255,204,0); border-radius: 5px; text-shadow: rgb(102, 102, 102) 1px 1px 1px; box-shadow: rgb(102, 102, 102) 1px 1px 2px;”><span style=”font-size: inherit; color: inherit; line-height: inherit; margin: 0px; padding: 0px;”> 思考 & 长图总结 ReentrantLock</span></h3></div>

咱们剖析 ReentrantLock 的加锁和开释锁,明天最初小结的一个思维其实就是:由脉络到细节,再从细节脉络。

另外 为了让大家更好的把握 ReentrantLock 的 AQS 原理。这里给大家总结了一下。,

首先能够把原理用一句话简略的讲:假如有两个线程同时进行获取锁的操作,只能有一个获取胜利,另一个会进入一个队列期待。底层是联合了 state、owner,Node 队列 AQS 的 3 个组件配合起来做到的。

ReentrantLock 外围加锁和开释流程能够总结为如下一张长图:

本文由博客一文多发平台 OpenWrite 公布!

正文完
 0