preface
Having seen the Lua script for reentrant locks, you can already see that locks fail when they exist.
Now let’s see, how to deal with the lock failure?
Lock Lua script
In the Lua script, the first two if paragraphs exclude two cases:
- Lock does not exist;
- The lock exists and is its own thread (reentrant);
The remaining case is that the lock exists, but not itself, which means that the lock failed.
Run the PTTL command to return the remaining time of lock.
Handling the lock failure
Source location: org. Redisson. RedissonLock# lock (long, Java. Util. Concurrent. TimeUnit, Boolean)
Let’s look at the beginning:
After the lock is successfully added, the system returns TTL, which is null.
So, the following section is the logic when the lock acquisition fails.
Ignore the logic that doesn’t need much attention, and focus on that little piece of while (true).
Keep calling the tryAcquire method in a loop until the lock succeeds!
conclusion
- The mutual exclusion of reentrant locks is guaranteed by Redis Lua scripts;
- Failure to lock returns the remaining time of the current lock.
- After the lock fails, the Java code keeps trying to lock using a while loop.
The general process is as follows:
Related to recommend
- Redisson distributed lock source code 02: watchdog
- 01: Reentrant lock add lock
- How did you resolve the Spring self-invocation transaction failure?