当前位置:网站首页>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();
}
边栏推荐
- Understanding of maximum likelihood estimation
- Why does the updated DNS record not take effect?
- Codeforces Round #649 (Div. 2)——A. XXXXX
- Euler Lagrange equation
- MySQL查询为什么没走索引?这篇文章带你全面解析
- Remote Sensing投稿经验分享
- common commands
- QT -- package the program -- don't install qt- you can run it directly
- Tapdata 的 2.0 版 ,開源的 Live Data Platform 現已發布
- Partage d'expériences de contribution à distance
猜你喜欢
Optimization of ecological | Lake Warehouse Integration: gbase 8A MPP + xeos
用户之声 | 冬去春来,静待花开 ——浅谈GBase 8a学习感悟
子矩阵的和
COMSOL - Construction of micro resistance beam model - final temperature distribution and deformation - establishment of geometric model
液压旋转接头的使用事项
About snake equation (5)
The function of carbon brush slip ring in generator
MATLAB R2021b 安装libsvm
Voice of users | understanding of gbase 8A database learning
pb9.0 insert ole control 错误的修复工具
随机推荐
滑环使用如何固定
The usage of rand function in MATLAB
break net
About snake equation (2)
Grey correlation analysis link (portal) matlab
神经网络与深度学习-5- 感知机-PyTorch
Tapdata 的 2.0 版 ,开源的 Live Data Platform 现已发布
Tapdata 的 2.0 版 ,开源的 Live Data Platform 现已发布
Write a pure handwritten QT Hello World
Introduction to natural language processing (NLP) based on transformers
Qt - - Packaging Programs - - Don't install Qt - can run directly
Tapdata 的 2.0 版 ,開源的 Live Data Platform 現已發布
body有8px的神秘边距
MySQL数据库(2)
Codeforces Round #643 (Div. 2)——B. Young Explorers
Plot function drawing of MATLAB
Redux usage
regular expression
nacos-微服务网关Gateway组件 +Swagger2接口生成
Optimization of ecological | Lake Warehouse Integration: gbase 8A MPP + xeos