学无先后,达者为师

网站首页 编程语言 正文

redisson分布式锁中waittime的设置

作者:蔚蓝色的风暴 更新时间: 2024-07-18 编程语言

之前分布式锁中使用redisson的lock.tryLock(0,0,TimeUnit.SECONDS)

这么做的逻辑是releaseTime设置为0,实际上会使用默认的30s并触发看门狗机制

那waitTime有没有默认值呢?设置为0实际会等待多少时间?

看源码

 public boolean tryLock(long waitTime, long leaseTime, TimeUnit unit) throws InterruptedException {
        long time = unit.toMillis(waitTime);
        long current = System.currentTimeMillis();
        long threadId = Thread.currentThread().getId();
        Long ttl = this.tryAcquire(waitTime, leaseTime, unit, threadId);
        if (ttl == null) {
            return true;
        } else {
            time -= System.currentTimeMillis() - current;
            if (time <= 0L) {
                this.acquireFailed(waitTime, unit, threadId);
                return false;
            } else {
            ........

这里的time直接就取的传入的waitTime,当time减少到小于0时,返回加锁失败!

所以waitTime是没有什么默认值的,这么写相当于加锁失败立刻返回

实验一下,先加一个不会过期的锁,然后另一个线程试图获取锁

@Test
    public void getLock() throws InterruptedException {
        String lockKey = "testLock";
        RLock lock = redissonClient.getLock(lockKey);
        System.out.println(System.currentTimeMillis());
        Boolean isLock = lock.tryLock(0,-1,TimeUnit.SECONDS);
        System.out.println(System.currentTimeMillis());
        System.out.println(isLock);
    }

如果设置为0,在尝试获取不到锁后立刻就会返回失败

原文链接:https://blog.csdn.net/qq_37831759/article/details/138490511

  • 上一篇:没有了
  • 下一篇:没有了
栏目分类
最近更新