当前位置:网站首页>Redisson分布式锁解锁异常
Redisson分布式锁解锁异常
2022-07-08 00:28:00 【知知之之】
问题现象
程序中的redission执行unlock()报错如下:
java.lang.IllegalMonitorStateException: attempt to unlock lock, not locked by current thread by node id:
从报错信息可知:尝试解锁,而不是由当前线程按节点 ID 锁定
问题复现
//获取锁对象
RLock lock = redissonClient.getLock(key);
try{
//获取锁
boolean tryLock = lock.tryLock(5, TimeUnit.SECONDS);
if (!tryLock) {
//抛出业务异常
}
}catch(){
//捕获异常
}finally{
//解锁
lock.unlock();
}排查过程
如上代码,线程无论是否有获取锁,都是需要去执行解锁方法,当线程没有获得锁,执行unlock()就会报java.lang.IllegalMonitorStateException: attempt to unlock lock, not locked by current thread by node id:错误
解决方案
1、在解锁时增加判断
//判断要解锁的key是否已被锁定;判断要解锁的key是否被当前线程持有
if (lock.isLocked() && lock.isHeldByCurrentThread()) {
lock.unlock();
}2、优化代码
在执行unlock()确保线程已经获得锁
//获取锁对象
RLock lock = redissonClient.getLock(key);
boolean tryLock;
try {
tryLock = lock.tryLock(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
throw new Exception("获取分布式锁失败,请稍后再试");
}
if (!tryLock) {
throw new Exception("请稍后再试");
}
try{
//抛出业务异常
}catch(){
//捕获异常
}finally{
//解锁
lock.unlock();
}边栏推荐
- 项目经理有必要考NPDP吗?我告诉你答案
- WPF 自定义 写实风 雷达图控件
- Why does the updated DNS record not take effect?
- 滑环在直驱电机转子的应用领域
- Why did MySQL query not go to the index? This article will give you a comprehensive analysis
- Break algorithm --- map
- cv2-drawline
- Chapter 7 behavior level modeling
- regular expression
- The function of carbon brush slip ring in generator
猜你喜欢

qt--将程序打包--不要安装qt-可以直接运行

为什么更新了 DNS 记录不生效?

Leetcode exercise - Sword finger offer 36 Binary search tree and bidirectional linked list

Capability contribution three solutions of gbase were selected into the "financial information innovation ecological laboratory - financial information innovation solutions (the first batch)"

给刚入门或者准备转行网络工程师的朋友一些建议

Apache multiple component vulnerability disclosure (cve-2022-32533/cve-2022-33980/cve-2021-37839)

Understanding of maximum likelihood estimation

3. Multi agent reinforcement learning

COMSOL----微阻梁模型的搭建---最终的温度分布和变形情况----几何模型的建立

滑环使用如何固定
随机推荐
用户之声 | 冬去春来,静待花开 ——浅谈GBase 8a学习感悟
剑指 Offer II 041. 滑动窗口的平均值
快手小程序担保支付php源码封装
SQLite3 data storage location created by Android
Urban land use distribution data / urban functional zoning distribution data / urban POI points of interest / vegetation type distribution
PB9.0 insert OLE control error repair tool
qt--将程序打包--不要安装qt-可以直接运行
Voice of users | understanding of gbase 8A database learning
Euler Lagrange equation
break net
由排行榜实时更新想到的数状数值
Get familiar with XML parsing quickly
神经网络与深度学习-5- 感知机-PyTorch
液压旋转接头的使用事项
Codeforces Round #649 (Div. 2)——A. XXXXX
Redux usage
Version 2.0 de tapdata, Open Source Live Data Platform est maintenant disponible
qt-使用自带的应用框架建立--hello world--使用min GW 32bit
如何让导电滑环信号更好
About snake equation (5)