ReentrantLock

ReentrantLock原理详解 文章目录前言一、ReentrantLock是如何实现的?二、lock 和 unlock的过程分析2.1 ReentrantLock的两个构造器2.2 lock过程2.3 unlock过程三、公平锁和非公平锁的区别四、Synchronized和ReentrantLock的区别4.1 功能区别4.2 性能区别4.3 ReentrantLock的特有性质 前言 了解ReentrantLock的原理和底层实现 一、ReentrantLock是如何实现的? ReentrantLock 主要利用CAS 和 AQS队列实 阅读详情

public class ReentrantLock

extends Object
implements Lock, Serializable

A reentrant mutual exclusion Lock with the same basic behavior and semantics as the implicit monitor lock accessed using synchronized methods and statements, but with extended capabilities.
A ReentrantLock is owned by the thread last successfully locking, but not yet unlocking it. A thread invoking lock will return, successfully acquiring the lock, when the lock is not owned by another thread. The method will return immediately if the current thread already owns the lock. This can be checked using methods isHeldByCurrentThread(), and getHoldCount().

The constructor for this class accepts an optional fairness parameter. When set true, under contention, locks favor granting access to the longest-waiting thread. Otherwise this lock does not guarantee any particular access order. Programs using fair locks accessed by many threads may display lower overall throughput (i.e., are slower; often much slower) than those using the default setting, but have smaller variances in times to obtain locks and guarantee lack of starvation. Note however, that fairness of locks does not guarantee fairness of thread scheduling. Thus, one of many threads using a fair lock may obtain it multiple times in succession while other active threads are not progressing and not currently holding the lock. Also note that the untimed tryLock method does not honor the fairness setting. It will succeed if the lock is available even if other threads are waiting.

It is recommended practice to always immediately follow a call to lock with a try block, most typically in a before/after construction such as:


 class X {
   private final ReentrantLock lock = new ReentrantLock();
   // ...

   public void m() {
     lock.lock();  // block until condition holds
     try {
       // ... method body
     } finally {
       lock.unlock()
     }
   }
 }

In addition to implementing the Lock interface, this class defines methods isLocked and getLockQueueLength, as well as some associated protected access methods that may be useful for instrumentation and monitoring.

Serialization of this class behaves in the same way as built-in locks: a deserialized lock is in the unlocked state, regardless of its state when serialized.

This lock supports a maximum of 2147483647 recursive locks by the same thread. Attempts to exceed this limit result in Error throws from locking methods.

ReentrantLock vs Synchronized

A ReentrantLock is unstructured, unlike synchronized constructs – i.e. you don’t need to use a block structure for locking and can even hold a lock across methods. An example:

private ReentrantLock lock;

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

public void bar() {
  ...
  lock.unlock();
  ...
}

Such flow is impossible to represent via a single monitor in a synchronized construct.

Aside from that, ReentrantLock supports lock polling and interruptible lock waits that support time-out. ReentrantLock also has support for configurable fairness policy, allowing more flexible thread scheduling.

The constructor for this class accepts an optional fairness parameter. When set true, under contention, locks favor granting access to the longest-waiting thread. Otherwise this lock does not guarantee any particular access order. Programs using fair locks accessed by many threads may display lower overall throughput (i.e., are slower; often much slower) than those using the default setting, but have smaller variances in times to obtain locks and guarantee lack of starvation. Note however, that fairness of locks does not guarantee fairness of thread scheduling. Thus, one of many threads using a fair lock may obtain it multiple times in succession while other active threads are not progressing and not currently holding the lock. Also note that the untimed tryLock method does not honor the fairness setting. It will succeed if the lock is available even if other threads are waiting.
ReentrantLock may also be more scalable, performing much better under higher contention. You can read more about this here.

This claim has been contested, however; see the following comment:

In the reentrant lock test, a new lock is created each time, thus there is no exclusive locking and the resulting data is invalid. Also, the IBM link offers no source code for the underlying benchmark so its impossible to characterize whether the test was even conducted correctly.

When should you use ReentrantLocks?

According to that developerWorks article…

The answer is pretty simple – use it when you actually need something it provides that synchronized doesn’t, like timed lock waits, interruptible lock waits, non-block-structured locks, multiple condition variables, or lock polling. ReentrantLock also has scalability benefits, and you should use it if you actually have a situation that exhibits high contention, but remember that the vast majority of synchronized blocks hardly ever exhibit any contention, let alone high contention. I would advise developing with synchronization until synchronization has proven to be inadequate, rather than simply assuming “the performance will be better” if you use ReentrantLock. Remember, these are advanced tools for advanced users. (And truly advanced users tend to prefer the simplest tools they can find until they’re convinced the simple tools are inadequate.) As always, make it right first, and then worry about whether or not you have to make it faster.

移远EC20模块USB模式切换的底层逻辑与驱动适配探秘 本文深入探讨了移远EC20模块USB模式切换的底层逻辑与驱动适配机制,详细解析了AT命令控制下的USB0与WWAN0模式差异。通过分析USB协议栈、内核驱动框架及网络子系统的交互,提供了模式切换的完整操作流程和常见问题解决方案,助力开发者优化4G通信模块在嵌入式设备中的稳定连接。 阅读详情

相关推荐

从像素到光影:解析《黑神话:悟空》中Nanite与Lumen的协同渲染革命

本文深度解析了《黑神话:悟空》如何利用Unreal Engine 5的Nanite与Lumen技术实现渲染革命。Nanite处理亿级多边形几何细节,无需传统LOD优化;Lumen提供全动态全局光照,实现实时光线反弹。两者协同工作,为游戏带来电影级视觉体验,重塑了实时渲染的技术标准与工作流程。

f6g7h8i9j的博客 425

ReentrantLock详解

ReentrantLock使用,

weixin_56738054的博客 1万+

RC模型车多电机驱动方案:从电调PWM原理到四电机安全连接实战

在电机控制领域,PWM(脉冲宽度调制)是实现精确调速的核心技术。其原理是通过调节固定周期内高电平的脉宽来编码控制指令,进而驱动电子调速器(电调)改变输出功率。这项技术对于需要多电机协同工作的场景,如RC模型车的差速转向或重型负载驱动,具有关键价值。它能实现动力的精细分配与同步,提升车辆的可控性与通过性。在实际应用中,为确保系统稳定,必须关注电流分配与信号同步问题。例如,通过为每个电机配备独立电调并采用信号并联(Y线)的方式,可以构建可靠的四电机驱动系统。这种方案能有效避免因单个电调过载或电机反电动势不一致导

weixin_30664615的博客 381

简单实现ReentrantLock,详解ReentrantLock底层原理

AbstractQueuedSynchronizer类不止服务于ReentrantLock类,因此该类里面有很多跟ReentrantLock不想关的代码存在,本文将提取ReentrantLock类和AbstractQueuedSynchronizer类的核心代码进行解释说明。本文末尾将附带经过我提取的手写的ReentrantLock代码,代码上附有我对该锁的理解的注解。的核心就是类,要了解就要先了解一、AbstractQueuedSynchronizer类。

duan614的博客 1897

深入解析Matlab phantom函数:从基础模体到自定义头部仿真

本文深入解析了Matlab中的phantom函数,它是医学图像处理算法测试的核心工具。文章详细介绍了如何使用内置的Shepp-Logan及其改良版头部仿真模体,并重点讲解了通过自定义参数矩阵来构建专属模体的方法。通过从生成模体到模拟投影(正弦图)再到图像重建的完整实战流程,展示了phantom函数在CT等算法开发与验证中的关键作用。

m3n5b7v8c9x的博客 948

三菱FX5U运动控制(步进)

三菱FX5U脉冲定位控制,原点回归,相对定位,绝对定位,运动控制案例。

weixin_55762091的博客 1万+

ReentrantLock面试总结

ReentrantLock面试总结

HRX98的博客 2296

STM32 使用IO口模拟I2C时序

上一篇《I2C协议详解》 我们了解了I2C的操作流程,这一篇,我们就使用I2C,来对EEPROM进行操作吧。 我们做两种选择: 1.时序由IO口模拟高低电平,需要了解协议并按照协议操作相应的IO口。 2.时序由硬件自行产生,不需要人工干预; 由硬件产生的I2C时序,我们借助Stm32Cube配置实现便可,我们这一篇,抛开Stm32Cube,手撕代码,根据I2C的时序,一步步地实现I2C对...

8937

ReentrantLock 底层原理

想弄懂 ReentrantLock 底层原理,这一篇就够了!包含 AQS底层原理,ReentrantLock公平锁、可重入、可打断的实现原理。

weixin_54232666的博客 4537

LabVIEW实战:基于DAQmx的实时正弦波生成、采集与波形图动态显示

本文详细介绍了如何使用LabVIEW和DAQmx驱动实现实时正弦波的生成、采集与动态显示。通过USB-6008数据采集卡,结合队列缓冲机制和动态波形图显示技术,构建了一个完整的信号处理系统。文章包含硬件连接、软件配置、任务设置及常见问题排查,适合LabVIEW初学者和硬件控制开发者参考。

weixin_30872337的博客 124

基于分数阶的图像边缘细节检测——边缘计算

在图像处理中,我们可以使用分数阶导数运算器来计算图像的分数阶梯度,从而得到更精确的边缘信息。通过使用基于分数阶的图像边缘细节检测方法,我们可以更准确地捕捉图像中的边缘细节信息。在这篇文章中,我们将介绍一种基于分数阶的方法来进行图像边缘细节检测,并提供相应的源代码实现。需要注意的是,以上提供的代码示例仅用于演示基于分数阶的图像边缘细节检测方法的实现。然后,我们读取了待处理的图像,并进行了预处理,如高斯模糊,以减少噪声的影响。最后,我们通过设置一个阈值,将梯度图像转化为二值化的边缘图像,并将结果显示出来。

GudcSql的博客 403

Synchronized vs ReentrantLock

摘要: 本文比较了Java中的两种锁机制:synchronized和ReentrantLock。synchronized是JVM内置的隐式锁,基于Monitor实现,支持锁升级(偏向锁→轻量级锁→重量级锁),使用简单但功能有限。ReentrantLock是显式锁,基于AQS实现,提供更丰富的功能如可中断、公平锁等。文章详细解析了synchronized的底层原理(包括字节码指令、锁状态转换)和ReentrantLock的AQS实现机制,并区分了对象锁(实例级别)和类锁(Class级别)的概念及其应用场景。

qq_41893505的博客 1238

C#解析基恩士(KEYENCE)PLC数据:KV协议通信与实时监控实现

KV协议是基恩士PLC使用的一种专用通信协议,通常用于与上位机进行数据交换。KV协议通过RS-232C、RS-485、Ethernet等接口与上位机通信,支持多种数据类型的读写,包括但不限于位、字、双字、浮点数等。简洁易用:KV协议的通信格式简单,易于实现。支持多种数据类型:支持位数据、字数据、定长字符串等。高效实时性:能够提供较高的实时数据交换性能,适合实时监控应用。本文介绍了如何通过C#与基恩士KV系列PLC进行通信,实现数据的解析和实时监控功能。

这里只有干货:从 Modbus 通信到 MES 对接,从 YOLO 训练到工控机部署,带你搞定工业软件开发全流程。 1806

Java ReentrantLock

1. 锁的意义——线程同步 2. 案例——基于ReentrantLock来实现同步 public class A { public static ReentrantLock reentrantLock = new ReentrantLock(); public static void main(String[] args) { new Thread(() -> { testSync(); }, "t1").start()

weixin_35821291的博客 5102

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

java的reentrantlock_JAVA中ReentrantLock详解

前言:本文解决的问题RentrantLock与Synchronized区别ReentrantLock特征ReentrantLock类的方法介绍1.什么是ReentrantLock1.1ReentrantLock 与Synchronized区别在面试中询问ReentrantLock与Synchronized区别时,一般回答都是ReentrantLockReentrantLock是JDK方法,需要手动...

weixin_39611043的博客 864

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

ReentrantLock的特点

一 概述 自JDK5起,Java类库中新提供了java.util.concurrent包,其中的java.util.concurrent.locks.Lock接口便成了Java的另一种全新的互斥同步手段。基于Lock接口,用户能够以非块结构(Non-Block Structured)来实现互斥同步,从而摆脱了语言特性的束缚,改为在类库层面去实现同步,这也为日后扩展出不同的调度算法,不同特征,不同性能,不同语义的各种锁。 二 ReentrantLock(重入锁) 重入锁(ReenturantLock)是

calm_encode的博客 1072

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

reentrantLock

重入的概念是什么,实现原理是什么?公平锁和非公平锁区别是什么,体现在哪些地方?没有竞争到锁的线程怎么实现等待,释放锁时又是怎么被唤醒的?发现没有是不是跟synchronized代码结构差不多,只是多了一个lock和unlock的过程。我们先画个图来对比一下synchronized和lock的数据结构:这就是学技术特别有趣的地方,你看多了感觉很多高大上的技术底层设计实际都差不多。ReentrantLock默认是非公平锁。

星坠竹空 693

ReentrantLock简单理解

ReentrantLock

qq_36138652的博客 2676

【源码解析】ReentrantLock

【源码解析】ReentrantLock

人类所有真实的快乐,一定是恒久的努力 1072
上一篇: Provider is not a pattern by Mark Seemann
下一篇: ExecutorService and Future
我把葡萄酿成酒
博客等级 码龄12年 275粉丝 198原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值