源码解析AQS的PROPAGATE有什么用?

2023-11-03 06:31
文章标签 源码 解析 aqs propagate

本文主要是介绍源码解析AQS的PROPAGATE有什么用?,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文章目录

  • AQS的PROPAGATE有什么用?
    • bug修复前的代码(Java 5)
      • 正常流程
      • 产生 bug 的情况
    • bug 修复后的代码 (java 7)

AQS的PROPAGATE有什么用?

image-20210909111158061

waitStatus=PROPAGATE值为-3,当前线程处在SHARED共享模式下,该字段才会使用

比如信号量Semaphore,读写锁ReentrantReadWriteLock的读锁等

这里用信号量Semaphore为例

bug修复前的代码(Java 5)

假设存在某次循环中队列里排队的结点情况为 head(-1)->t1(-1)->t2(-1)
假设存在将要信号量释放的 T3 和 T4,释放顺序为先 T3 后 T4

正常流程

image-20210927231919393

产生 bug 的情况

image-20210927231940553

修复前版本执行流程

  1. T3 调用 releaseShared(1),直接调用了 unparkSuccessor(head),head 的等待状态从 -1 变为 0
public final boolean releaseShared(int arg)
{if(tryReleaseShared(arg)){Node h = head;if(h != null && h.waitStatus != 0) unparkSuccessor(h);return true;}return false;
}
private void unparkSuccessor(Node node) {/** If status is negative (i.e., possibly needing signal) try* to clear in anticipation of signalling.  It is OK if this* fails or if status is changed by waiting thread.*/int ws = node.waitStatus;if (ws < 0)compareAndSetWaitStatus(node, ws, 0);//哨兵节点的waitStatus从-1改为0/** Thread to unpark is held in successor, which is normally* just the next node.  But if cancelled or apparently null,* traverse backwards from tail to find the actual* non-cancelled successor.*/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)//唤醒t1LockSupport.unpark(s.thread);
}
  1. T1 由于 T3 释放信号量被唤醒,调用 tryAcquireShared,假设返回值为 0(获取锁成功,但没有剩余资源
    量)
private void doAcquireShared(int arg)
{final Node node = addWaiter(Node.SHARED);boolean failed = true;try{boolean interrupted = false;for(;;){final Node p = node.predecessor();if(p == head){int r = tryAcquireShared(arg);//尝试获取资源 获取资源成功返回0  该场景t1会在这里停留一段时间,t4 释放资源,t1才获取锁成功if(r >= 0){// 这里会有空档  setHeadAndPropagate(node, r);p.next = null; // help GCif(interrupted) selfInterrupt();failed = false;return;}}if(shouldParkAfterFailedAcquire(p, node) && parkAndCheckInterrupt()) interrupted = true;}}finally{if(failed) cancelAcquire(node);}
}

tryAcquireShared(arg)的实现方法

final int nonfairTryAcquireShared(int acquires) {for (;;) {int available = getState();//1int remaining = available - acquires;//0if (remaining < 0 ||compareAndSetState(available, remaining))//1改为0return remaining;}
}
  1. T4 释放资源调用 releaseShared(1),此时 head.waitStatus 为 0(此时读到的 head 和 1 中为同一个head),不满足条件,因此不调用 unparkSuccessor(head)
public final boolean releaseShared(int arg)
{if(tryReleaseShared(arg)){Node h = head;if(h != null && h.waitStatus != 0) unparkSuccessor(h);return true;}return false;
}
  1. T1 获取信号量成功,调用 setHeadAndPropagate 时,因为不满足 propagate > 0(2 的返回值也就是propagate(剩余资源量) == 0),从而不会唤醒后继结点, T2 线程得不到唤醒
private void doAcquireShared(int arg)
{final Node node = addWaiter(Node.SHARED);boolean failed = true;try{boolean interrupted = false;for(;;){final Node p = node.predecessor();if(p == head){int r = tryAcquireShared(arg); if(r >= 0){// 这里会有空档  假设在这里停留一段时间//等到t4释放了资源才执行到 setHeadAndPropagate(node, r)setHeadAndPropagate(node, r);//此时state是 tryAcquireShared(arg)返回的0,而非t4释放后的1p.next = null; // help GCif(interrupted) selfInterrupt();failed = false;return;}}if(shouldParkAfterFailedAcquire(p, node) && parkAndCheckInterrupt()) interrupted = true;}}finally{if(failed) cancelAcquire(node);}
}
private void setHeadAndPropagate(Node node, int propagate)
{setHead(node);// 传过来的propagate=0 ,就无法唤醒t2了。if(propagate > 0 && node.waitStatus != 0){Node s = node.next;// 下一个if(s == null || s.isShared()) unparkSuccessor(node);}
}

总结:

t3释放资源,会唤醒哨兵节点的后继节点t1尝试获取锁,并将哨兵节点的waitStatus改为0

在t1获取锁,t4释放资源,并唤醒哨兵节点的后继节点(此时t1还未获取到锁,所以这里唤醒的还是t1),此时哨兵节点的waitStatus=0唤醒失败。

当t1获得锁成功后,此时将t1所在的节点作为新的哨兵节点(waitStatus=-1),GC回收旧的哨兵节点,

由于此时传过来的propagate是t1获取锁成功的返回值0(实际此时state=1),就无法继续唤醒t2

bug 修复后的代码 (java 7)

image-20210927232224767

  1. T3 调用 releaseShared(),直接调用了 unparkSuccessor(head),head 的等待状态从 -1 变为 0
public final boolean releaseShared(int arg) {if (tryReleaseShared(arg)) {doReleaseShared();return true;}return false;
}
private void doReleaseShared() {/** Ensure that a release propagates, even if there are other* in-progress acquires/releases.  This proceeds in the usual* way of trying to unparkSuccessor of head if it needs* signal. But if it does not, status is set to PROPAGATE to* ensure that upon release, propagation continues.* Additionally, we must loop in case a new node is added* while we are doing this. Also, unlike other uses of* unparkSuccessor, we need to know if CAS to reset status* fails, if so rechecking.*/// 如果 head.waitStatus == Node.SIGNAL(-1) ==> 0 成功, 下一个节点 unpark// 如果 head.waitStatus == 0 ==> Node.PROPAGATE(-3)for (;;) {Node h = head;if (h != null && h != tail) {int ws = h.waitStatus;if (ws == Node.SIGNAL) {if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0))continue;            // loop to recheck casesunparkSuccessor(h);//唤醒后继节点}else if (ws == 0 &&!compareAndSetWaitStatus(h, 0, Node.PROPAGATE))continue;                // loop on failed CAS}if (h == head)                   // loop if head changedbreak;}
}
private void unparkSuccessor(Node node) {/** If status is negative (i.e., possibly needing signal) try* to clear in anticipation of signalling.  It is OK if this* fails or if status is changed by waiting thread.*/int ws = node.waitStatus;if (ws < 0)compareAndSetWaitStatus(node, ws, 0);//哨兵节点的waitStatus从-1改为0/** Thread to unpark is held in successor, which is normally* just the next node.  But if cancelled or apparently null,* traverse backwards from tail to find the actual* non-cancelled successor.*/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);
}
  1. T1 由于 T3 释放信号量被唤醒,调用 tryAcquireShared,假设返回值为 0(获取锁成功,但没有剩余资源
    量)
private void doAcquireSharedInterruptibly(int arg)throws InterruptedException {final Node node = addWaiter(Node.SHARED);boolean failed = true;try {for (;;) {final Node p = node.predecessor();//前驱节点if (p == head) {int r = tryAcquireShared(arg);//获取锁成功返回0if (r >= 0) {//此时t4释放锁 t1停留一段时间setHeadAndPropagate(node, r);//t1,0p.next = null; // help GCfailed = false;return;}}if (shouldParkAfterFailedAcquire(p, node) &&parkAndCheckInterrupt())throw new InterruptedException();}} finally {if (failed)cancelAcquire(node);}
}
  1. T4 调用 releaseShared(),此时 head.waitStatus 为 0(此时读到的 head 和 1 中为同一个 head),调用doReleaseShared() 将等待状态置为PROPAGATE(-3)
public final boolean releaseShared(int arg) {if (tryReleaseShared(arg)) {doReleaseShared();return true;}return false;
}
private void doReleaseShared() {/** Ensure that a release propagates, even if there are other* in-progress acquires/releases.  This proceeds in the usual* way of trying to unparkSuccessor of head if it needs* signal. But if it does not, status is set to PROPAGATE to* ensure that upon release, propagation continues.* Additionally, we must loop in case a new node is added* while we are doing this. Also, unlike other uses of* unparkSuccessor, we need to know if CAS to reset status* fails, if so rechecking.*/// 如果 head.waitStatus == Node.SIGNAL(-1) ==> 0 成功, 下一个节点 unpark// 如果 head.waitStatus == 0 ==> Node.PROPAGATE(-3)for (;;) {Node h = head;if (h != null && h != tail) {int ws = h.waitStatus;//0if (ws == Node.SIGNAL) {if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0))continue;            // loop to recheck casesunparkSuccessor(h);//唤醒后继节点}//waitStatus将0改为-3  else if (ws == 0 &&!compareAndSetWaitStatus(h, 0, Node.PROPAGATE))continue;                // loop on failed CAS}//都不满足。结束自旋if (h == head)                   // loop if head changedbreak;}
}
  1. T1 获取锁成功,调用 setHeadAndPropagate 时,读到 h.waitStatus < 0,从而调用doReleaseShared() 唤醒 T2
private void setHeadAndPropagate(Node node, int propagate)//t1 ,0
{Node h = head; // Record old head for check below //旧的哨兵节点// 设置自己为 headsetHead(node);//t1变为新的哨兵节点 此时的哨兵节点的waitStatus=-1// propagate 表示有共享资源(例如共享读锁或信号量)//  head waitStatus == Node.SIGNAL 或 Node.PROPAGATE//h.waitStatus=-3if(propagate > 0 || h == null || h.waitStatus < 0 || (h = head) == null || h.waitStatus < 0){Node s = node.next;//t2// 如果是最后一个节点或者是等待共享读锁的节点if(s == null || s.isShared()){//唤醒t2doReleaseShared();}}
}
private void doReleaseShared() {/** Ensure that a release propagates, even if there are other* in-progress acquires/releases.  This proceeds in the usual* way of trying to unparkSuccessor of head if it needs* signal. But if it does not, status is set to PROPAGATE to* ensure that upon release, propagation continues.* Additionally, we must loop in case a new node is added* while we are doing this. Also, unlike other uses of* unparkSuccessor, we need to know if CAS to reset status* fails, if so rechecking.*/for (;;) {Node h = head;if (h != null && h != tail) {int ws = h.waitStatus;//-1if (ws == Node.SIGNAL) {if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0))continue;            // loop to recheck casesunparkSuccessor(h);//唤醒t2}else if (ws == 0 &&!compareAndSetWaitStatus(h, 0, Node.PROPAGATE))continue;                // loop on failed CAS}if (h == head)                   // loop if head changedbreak;}
}

总结:

t3释放资源,会唤醒哨兵节点的后继节点t1尝试获取锁,并将哨兵节点的waitStatus改为0

在t1获取锁,t4释放资源,并唤醒哨兵节点的后继节点,此时判断哨兵节点的waitStatus=0,会将waitStatus改为PROPAGATE(-3)。此时所有条件都不满足结束

当t1获得锁成功后,只要 head waitStatus == Node.SIGNAL 或 Node.PROPAGATE满足一个条件 都会唤醒t2(前提是哨兵节点的后继节点t2是共享模式 或者为null)

PROPAGATE(-3)保证当一个线程被唤醒获取锁成功到将这个线程节点当做新的哨兵节点,回收旧哨兵节点的过程中,如果又有资源得到释放,不会再执行多余的唤醒操作

因为当这个线程获取锁后会尝试唤醒他的后继节点(共享模式的节点)

这篇关于源码解析AQS的PROPAGATE有什么用?的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/336255

相关文章

8种快速易用的Python Matplotlib数据可视化方法汇总(附源码)

《8种快速易用的PythonMatplotlib数据可视化方法汇总(附源码)》你是否曾经面对一堆复杂的数据,却不知道如何让它们变得直观易懂?别慌,Python的Matplotlib库是你数据可视化的... 目录引言1. 折线图(Line Plot)——趋势分析2. 柱状图(Bar Chart)——对比分析3

使用Java实现Navicat密码的加密与解密的代码解析

《使用Java实现Navicat密码的加密与解密的代码解析》:本文主要介绍使用Java实现Navicat密码的加密与解密,通过本文,我们了解了如何利用Java语言实现对Navicat保存的数据库密... 目录一、背景介绍二、环境准备三、代码解析四、核心代码展示五、总结在日常开发过程中,我们有时需要处理各种软

Python多进程、多线程、协程典型示例解析(最新推荐)

《Python多进程、多线程、协程典型示例解析(最新推荐)》:本文主要介绍Python多进程、多线程、协程典型示例解析(最新推荐),本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定... 目录一、multiprocessing(多进程)1. 模块简介2. 案例详解:并行计算平方和3. 实现逻

Spring Boot拦截器Interceptor与过滤器Filter深度解析(区别、实现与实战指南)

《SpringBoot拦截器Interceptor与过滤器Filter深度解析(区别、实现与实战指南)》:本文主要介绍SpringBoot拦截器Interceptor与过滤器Filter深度解析... 目录Spring Boot拦截器(Interceptor)与过滤器(Filter)深度解析:区别、实现与实

MyBatis分页插件PageHelper深度解析与实践指南

《MyBatis分页插件PageHelper深度解析与实践指南》在数据库操作中,分页查询是最常见的需求之一,传统的分页方式通常有两种内存分页和SQL分页,MyBatis作为优秀的ORM框架,本身并未提... 目录1. 为什么需要分页插件?2. PageHelper简介3. PageHelper集成与配置3.

SQL 外键Foreign Key全解析

《SQL外键ForeignKey全解析》外键是数据库表中的一列(或一组列),用于​​建立两个表之间的关联关系​​,外键的值必须匹配另一个表的主键(PrimaryKey)或唯一约束(UniqueCo... 目录1. 什么是外键?​​ ​​​​2. 外键的语法​​​​3. 外键的约束行为​​​​4. 多列外键​

Java进行日期解析与格式化的实现代码

《Java进行日期解析与格式化的实现代码》使用Java搭配ApacheCommonsLang3和Natty库,可以实现灵活高效的日期解析与格式化,本文将通过相关示例为大家讲讲具体的实践操作,需要的可以... 目录一、背景二、依赖介绍1. Apache Commons Lang32. Natty三、核心实现代

使用Python自动化生成PPT并结合LLM生成内容的代码解析

《使用Python自动化生成PPT并结合LLM生成内容的代码解析》PowerPoint是常用的文档工具,但手动设计和排版耗时耗力,本文将展示如何通过Python自动化提取PPT样式并生成新PPT,同时... 目录核心代码解析1. 提取 PPT 样式到 jsON关键步骤:代码片段:2. 应用 JSON 样式到

Maven 插件配置分层架构深度解析

《Maven插件配置分层架构深度解析》:本文主要介绍Maven插件配置分层架构深度解析,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录Maven 插件配置分层架构深度解析引言:当构建逻辑遇上复杂配置第一章 Maven插件配置的三重境界1.1 插件配置的拓扑

全解析CSS Grid 的 auto-fill 和 auto-fit 内容自适应

《全解析CSSGrid的auto-fill和auto-fit内容自适应》:本文主要介绍了全解析CSSGrid的auto-fill和auto-fit内容自适应的相关资料,详细内容请阅读本文,希望能对你有所帮助... css  Grid 的 auto-fill 和 auto-fit/* 父元素 */.gri