当前位置:   article > 正文

Redisson分布式锁解锁异常_java.lang.illegalmonitorstateexception: attempt to

java.lang.illegalmonitorstateexception: attempt to unlock lock, not locked b

问题现象

程序中的redission执行unlock()报错如下:

java.lang.IllegalMonitorStateException: attempt to unlock lock, not locked by current thread by node id:

从报错信息可知:尝试解锁,而不是由当前线程按节点 ID 锁定

问题复现

  1. //获取锁对象
  2. RLock lock = redissonClient.getLock(key);
  3. try{
  4. //获取锁
  5. boolean tryLock = lock.tryLock(5, TimeUnit.SECONDS);
  6. if (!tryLock) {
  7. //抛出业务异常
  8. }
  9. }catch(){
  10. //捕获异常
  11. }finally{
  12. //解锁
  13. lock.unlock();
  14. }

排查过程

如上代码,线程无论是否有获取锁,都是需要去执行解锁方法,当线程没有获得锁,执行unlock()就会报java.lang.IllegalMonitorStateException: attempt to unlock lock, not locked by current thread by node id:错误

解决方案

1、在解锁时增加判断

  1. //判断要解锁的key是否已被锁定;判断要解锁的key是否被当前线程持有
  2. if (lock.isLocked() && lock.isHeldByCurrentThread()) {
  3. lock.unlock();
  4. }

2、优化代码

在执行unlock()确保线程已经获得锁

  1. //获取锁对象
  2. RLock lock = redissonClient.getLock(key);
  3. boolean tryLock;
  4. try {
  5. tryLock = lock.tryLock(5, TimeUnit.SECONDS);
  6. } catch (InterruptedException e) {
  7. throw new Exception("获取分布式锁失败,请稍后再试");
  8. }
  9. if (!tryLock) {
  10. throw new Exception("请稍后再试");
  11. }
  12. try{
  13. //抛出业务异常
  14. }catch(){
  15. //捕获异常
  16. }finally{
  17. //解锁
  18. lock.unlock();
  19. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Guff_9hys/article/detail/965599
推荐阅读
相关标签
  

闽ICP备14008679号