Home > Back-end >  RLock#lock(long leaseTime, TimeUnit unit) leasetime lower than execution time
RLock#lock(long leaseTime, TimeUnit unit) leasetime lower than execution time

Time:11-26

Code:

public void lock() {
    RLock lock = redissonClient.getLock("lock");
    lock.lock(1, TimeUnit.SECONDS); // or use lock.lock()
    doSomething();
    lock.unlock(); // if necessary
}

If doSomething() spending time over 1s(reason like network), then another thread can get the lock, but this will cause some problems (such as oversold). If use lock.lock(), while this client offline, it will never unlock the lock and others client can not get the lock. How to solve or balance this problem?

CodePudding user response:

If use lock.lock(), while this client offline, it will never unlock the lock and others client can not get the lock.

When you use lock#lock(), an expiration time will be set on the corresponding key (the default is 30 seconds, see org.redisson.config.Config#lockWatchdogTimeout), and there will be a watchdog(watchdog is actually a timer task) that is always responsible for the automatic extension(extend the expiration time of the corresponding key).

So if your client is suddenly disconnected, then the lock will be released after a certain period of time (that is, the corresponding key has expired because watchdog also hangs up with your client ). So you don’t have to worry about the problem that the lock will never be released if you use lock#lock().

  • Related