This is my first day to participate in the Novembermore Challenge

preface

In practice, some logic is called only once at the same time, in order to prevent repeated data production caused by multiple inserts. This kind of concurrency problem, we often think of the first time is Java synchronized, lock to solve, but this premise is under the same JVM, then how to solve in the distributed cluster scenario?

A distributed lock

As the name implies, locks are used in distributed scenarios. In simple terms, locks are managed by a third party (REDis). Each node of distributed services obtains locks from Redis, and whoever gets the locks will deal with them.

RedissonLock

Continue to lock

If the validity period of a distributed lock is shorter than the service execution time (which is unpredictable), the lock will be released in advance, causing repeated service logic execution. If the validity period is set to permanent, the lock cannot be released during service downtime or restart. As a result, subsequent services are affected. RedissonLock implements the ability to automatically reset the lock validity period when the service execution is not complete. To solve these two problems.

The RedissonLock logic is implemented using the Netty Timeout timer. The default lock time is 30 seconds, and the timer is executed every 10 seconds /3. To determine whether the lock is still held. If it is still held, the lock is reset for 30 seconds. In this way, the lock is released because the service execution time is longer than the lock time.

Source:However, when we use the lock in this way, we will find that the lock cannot be renewed automatically

boolean isLock = lock.tryLock(6, 6, TimeUnit.SECONDS);

The first parameter, 6, indicates that the lock is valid for 6, the second parameter, 6, indicates that the timeout period for blocking to wait for acquisition is 6, and the third parameter is a unit of time.

In theory, according to the rules of lock renewal, should be every 2 seconds to determine whether the lock is still held, but why did not execute it? The problem is this one line of code

There is a logic judgment, if the validity of the custom the lock will only perform tryLockInnerAsync method, and not to renew their scheduleExpirationRenewal lock method.

conclusion

When using the lock renewal function, remember not to set the lock expiration time, can be set to -1. Once the time is set, RedissonLock assumes that you need to control the lock time yourself and does not perform the lock continuation logic. View the source code, it is not difficult to find the continuation of the lock logic overhead is quite large, the need for a timer. So keep in mind that not all distributed scenarios require continued locking logic. When it is difficult to determine the execution time of the business logic, it is useful to enable the continuation lock.