preface

In the last article has analyzed the fair lock lock source code, and come to the conclusion:

  1. Redis Hash data structure: stores the current lock. The Redis Key is the lock, the Hash field is the lock thread, and the Hash value is the reentrant count.
  2. Redis List data structure: acts as a thread wait queue. New wait threads are placed to the right of the queue using rpush.
  3. Redis sorted set Ordered collection data structure: Store the order of waiting threads. Score is used as timeout stamp for waiting threads.

Now let’s see what happens to the thread after the lock failure is put on the wait queue.

Waiting in line for the lock

Source: entrance org. Redisson. RedissonLock# lock (long, Java. Util. Concurrent. TimeUnit, Boolean).

After the thread enters the queue, in Java code it will loop through tryAcquire while (true) trying to acquire the lock.

We end up in the RedissonFairLock#tryLockInnerAsync method.

For convenience, repaste the Lua script and the meaning of its parameters.

  1. KEYS[1] : the name of the lockanyLock;
  2. KEYS[2] : lock wait queue,redisson_lock_queue:{anyLock};
  3. KEYS[3] : set of waiting for the thread lock time in the queue,redisson_lock_timeout:{anyLock}Is stored in the collection according to the timestamp of the lock;
  4. ARGV[1] : lock timeout time 30000
  5. ARGV[2] : UUID:ThreadId combinationa3da2c83-b084-425c-a70f-5d9a08b37f31:1
  6. ARGV[3] : threadWaitTime defaults to 300000
  7. ARGV[4] : currentTime Indicates the current timestamp

Source code analysis

Part one, the while loop:

  1. From the wait queueredisson_lock_queue:{anyLock}To get the first waiting thread;
  2. From the waiting thread timeout collectionredisson_lock_timeout:{anyLock}Get the score of the first waiting thread;
  3. If there is no timeout, it will end. If there is a timeout, it will be removed.

In the second part, the current lock exists and is skipped.

The third part, the current lock is not the thread holding the lock, directly skip.

Part four,

Returns how long the current lock will expire.

The current version of Redisson is 3.15.6, with slightly different versions.

A rearrangement of the queue

There is no reordering, because it is officially considered a bug and has been refixed.

Justin Corpron 2019/5/10, 04:13 Fix timeout drift in RedissonFairLock

The biggest change is the addition of a fourth part.

The diagram only represents the differences between the two versions, not the changes made to each version.

conclusion

When the thread fails to acquire the lock and enters the wait queue, TTL! = null, in Java code will constantly try to acquire the lock.

The lock is acquired when the lock does not exist and the current thread is waiting on the queue header. This queuing process is the withdrawal of fair lock.

Related to recommend

  • Redisson distributed lock source 05: fair lock lock
  • 04: Reentrant lock release
  • Reentrant locks are mutually exclusive