1. Locking process
Low-level commands and data structures
-
Redis Data Structure: Use a Hash structure to store lock information, Key is the lock name, and Field is the client's unique identifier (such as
UUID + Thread ID
), Value is the number of reentries of the lock. - Lua script atomicity: Execute locking logic atomically in Redis through Lua scripts:
if (('exists', KEYS[1]) == 0) then ('hincrby', KEYS[1], ARGV[2], 1); ('pexpire', KEYS[1], ARGV[1]); return nil; end; if (('hexists', KEYS[1], ARGV[2]) == 1) then ('hincrby', KEYS[1], ARGV[2], 1); ('pexpire', KEYS[1], ARGV[1]); return nil; end; return ('pttl', KEYS[1]);
- If the lock does not exist (
exists
is 0) or belongs to the current thread (hexists
is 1), then the number of reentries is increased and the expiration time is refreshed. - If the lock is occupied by other threads, return the remaining survival time (TTL) of the lock.
Reentrability
When the same thread acquires the lock multiple times, the number of reentries is incremented to ensure that there is no deadlock due to multiple locking.
2. Automatic lock renewal (Watchdog mechanism)
- Background thread renewal: After the lock is successfully added, start a Watchdog thread (watchdog) and check regularly (default every 10 seconds) to check whether the lock is still held.
-
Renewal conditions: Only when the client still holds the lock and the business is not completed, pass
pexpire
The command resets the lock's expiration time to its initial value (default 30 seconds). - Crash error tolerance: If the client crashes, the Watchdog thread stops, and the lock will be automatically released due to expire, avoiding deadlock.
3. Release the lock
Release logic
Lua script atomic release:
if (('hexists', KEYS[1], ARGV[3]) == 0) then return nil; end; local counter = ('hincrby', KEYS[1], ARGV[3], -1); if (counter > 0) then ('pexpire', KEYS[1], ARGV[2]); return 0; else ('del', KEYS[1]); ('publish', KEYS[2], ARGV[1]); return 1; end; return nil;
- Reduce the number of reentries, delete the lock if the number of times is zero, and wait for the thread through Pub/Sub.
- Make sure only the lock holder can release the lock and avoid mistaken deletion.
4. Lock competition and waiting
- Spin retry: If the lock is occupied, the client enters the loop and attempts to add the lock intermittently.
-
Pub/Sub subscription notifications: Release events through subscription lock (
redisChannel
) to avoid frequent polling. When the lock is released, Redis issues a message notification to wait for threads to compete for the lock, reducing invalid requests.
5. High availability and fault tolerance Redis deployment mode
- Single node mode: Simple but with a single point of failure risk.
-
Master-slave/cluster mode:use
RedissonMultiLock
Implement the RedLock algorithm (requires multiple independent Redis nodes):- Apply for locks to all nodes in sequence.
- When most nodes successfully lock and the total time is less than the lock timeout time, locking is considered successful.
- Avoid the problem of lock loss caused by master-slave switching, but trade-offs on performance and consistency.
6. Key considerations
- Business execution time: The business logic must be completed within the expiration time of the lock, otherwise the lock may be released in advance.
- Clock synchronization problem: In RedLock, if the clock between Redis nodes is not synchronized, the lock may fail.
- Network delay: In extreme cases, the lock may be held by multiple clients at the same time (need to be handled in conjunction with business idempotence).
Summarize
- Redisson distributed lock passesThe atomicity of Lua scripts、Reentrant design、Watchdog automatic renewalandPub/Sub Notification Mechanism, realizes efficient distributed lock management. Its core advantages are:
- Avoid accidentally deleting locks (only the holder can release).
- Supports reentrability and adapts to complex business logic.
- Automatic renewal prevents locks from expired when business is not completed.
- Supports highly available scenarios through RedLock, but the trade-offs should be carefully weighed against consistency and performance.
This is the end of this article about the commonly used distributed lock Redisson in JAVA. For more related content on Java distributed lock Redisson, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!