preface

As you have seen, reentrant lock locking, guard dog, and lock mutually exclusive blocking.

How is the lock released after it is successfully locked?

Take the initiative to release

RedissonLock#unlock

The id of the current thread is obtained when unlocked.

Go all the way down to RedissonLock#unlockInnerAsync:

Analyze the contents of the Lua script:

  1. If the lock does not exist, null is returned.
  2. If a lock exists, the reentrant count of the lock is -1.
    1. If the remaining reentrant times are greater than 0, reset the expiration time and return 0.
    2. If the remaining reentrant times are not greater than 0, delete the Redis key and publish the message, and return 1.

The active lock release takes into account not only the key processing, but also the hash value corresponding to the redis key is decrement, i.e. the number of reentrant times.

Automatic release

Automatic release is easier to understand than active release.

  1. When the service is down and the watchdog is no longer guarding the door, the lock is automatically released after a maximum of 30 seconds.
  2. When the lock time is set, the lock is automatically released when the time is up.

conclusion

Redisson locks are released in two ways:

  1. Active release: call API unlock;
  2. Downtime/Expiration Automatic release: The Redis key automatically expires at the specified time.

Related to recommend

  • Reentrant locks are mutually exclusive
  • Redisson distributed lock source code 02: watchdog
  • 01: Reentrant lock add lock