springboot-note icon indicating copy to clipboard operation
springboot-note copied to clipboard

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

Open li-shaoke opened this issue 4 years ago • 1 comments

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); } }

li-shaoke avatar Jan 06 '21 05:01 li-shaoke

这个线程判断的逻辑是的确是之前欠考虑了,后面做了新的一版,是让正在运行中的任务一直续时,这样其他线程就不可能获取到同一个锁。

具体还有很多可以优化的点,欢迎你的讨论,一起改善~

Vip-Augus avatar Jan 06 '21 16:01 Vip-Augus