Skip to content

释放锁代码存在问题,会存在超时操作释放了本次操作的锁 #2

Description

@li-shaoke
finally {
        // 请求结束后,强制删掉 key,释放锁
        redisTemplate.delete(businessKey);
        log.info("release the lock, businessKey is [" + businessKey + "]");
    }

如果A线程锁操作超时了,但是还在执行,此时B线程进入了拿到锁并进行操作,此时A线程去释放锁,释放的就是B此时持有的锁。
此处应该加入判断,来释放锁的线程是否是持有锁的那个线程。
可以改成
finally {
try {
RedisLockDefinitionHolder redisLockDefinitionHolder = holderList.stream().filter(h -> businessKey.equals(h.getBusinessKey())).findFirst().orElse(null);
if (redisLockDefinitionHolder != null && redisLockDefinitionHolder.getCurrentTread().equals(currentThread)){
// 请求结束后,强制删掉 key,释放锁
redisTemplate.delete(businessKey);
log.info("release the lock, businessKey is [" + businessKey + "]");
}
}catch(Exception e){
log.error("release the lock error", e);
}
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions