Redisson分布式锁报错:attempt to unlock lock, not locked by current thread by node id

Redisson分布式锁报错:attempt to unlock lock, not locked by current thread by node id

java.lang.IllegalMonitorStateException: attempt to unlock lock, not locked by current thread by node id: 193fa0a4-1df0-445f-8737-18b7bb464f64 thread-id: 80

Redission分布式锁进行unlock操作时,有个异常源码如下:

public void unlock() {
        try {
            this.get(this.unlockAsync(Thread.currentThread().getId()));
        } catch (RedisException var2) {
            if (var2.getCause() instanceof IllegalMonitorStateException) {
                throw (IllegalMonitorStateException)var2.getCause();
            } else {
                throw var2;
            }
        }
    }
public RFuture<Void> unlockAsync(long threadId) {
        RFuture<Boolean> future = this.unlockInnerAsync(threadId);
        CompletionStage<Void> f = future.handle((opStatus, e) -> {
            this.cancelExpirationRenewal(threadId);
            if (e != null) {
                throw new CompletionException(e);
            } else if (opStatus == null) {
                IllegalMonitorStateException cause = new IllegalMonitorStateException("attempt to unlock lock, not locked by current thread by node id: " + this.id + " thread-id: " + threadId);
                throw new CompletionException(cause);
            } else {
                return null;
            }
        });
        return new CompletableFutureWrapper(f);
    }

为什么会这样,由于在进行lock操作时,会设置一个时间

1.当你在完成lock后,里面的业务代码执行时间大于lock时间时,进行unlock,会抛出该异常

2.多线程竞争的问题,当第一个线程完成lock,此时并未 unlock,如此,第二个线程尝试获取锁,并进行lock操作,会抛出该异常。

解决办法:

在lock或unlock前,判断下状态合法性即可,而非直接进行加锁解锁操作。

posted @ 2022-09-14 11:12  EmptyJar  阅读(6811)  评论(0)    收藏  举报