How Redisson Implements Distributed Locks: A Deep Dive into Lua Scripts and Watchdog Mechanism
This article explains how Redisson builds a robust Redis‑based distributed lock by using Lua scripts for atomic operations, a watchdog to auto‑extend leases, support for re‑entrant, fair, read‑write, multi‑lock and RedLock algorithms, and shows the relevant Java code snippets.
In a distributed system, traditional single‑process locking APIs such as synchronized or ReentrantLock are insufficient, so a distributed lock is required to coordinate multiple service instances. Redis is a popular choice, and Redisson provides a feature‑rich implementation.
1. Ensuring Atomicity
Redisson does not rely on the simple SETNX command; instead it implements its own locking logic. The lock is obtained via RedissonClient.getLock(name), which returns an RLock instance that delegates to RedissonLock. The lock() method ultimately calls tryAcquire, which forwards to tryAcquireAsync and then to tryLockInnerAsync.
2. Using Lua Scripts for Locking
The actual lock acquisition is performed by a Lua script executed atomically on Redis. The script receives KEYS[1] (the lock name), ARGV[1] (lease time, default 30 s), and ARGV[2] (a unique identifier composed of a client UUID and thread ID). It first checks EXISTS, then uses HINCRBY to store the lock count, and finally sets an expiration with PEXPIRE.
3. Why a Lease Time Is Needed
Redisson sets a default 30 s expiration to avoid deadlocks when a client crashes before releasing the lock. Without an expiration, a stale lock would block other threads indefinitely.
4. Automatic Lease Extension (Watchdog)
If no explicit lease time is provided, Redisson starts a watchdog task that renews the lock every 10 seconds by executing another Lua script, extending the expiration to 30 s each time.
5. Re‑entrant Locking
When the same client thread attempts to lock again, the Lua script detects the existing entry and increments the lock count, allowing re‑entrancy.
6. Unlocking Safely
Unlocking is performed via unlock(), which calls unlockAsync and ultimately runs a Lua script that verifies the caller’s identifier, decrements the lock count, and deletes the key when the count reaches zero.
7. Timeout‑Based Automatic Release
When a lease time is supplied (e.g., lock(long leaseTime, TimeUnit unit)), the watchdog is not started; the lock simply expires after the given period.
8. Fair Lock
Redisson provides a fair lock via getFairLock, implemented by RedissonFairLock, which queues waiting threads in a Redis set to guarantee FIFO ordering.
9. Read‑Write Lock
Using RedissonReadWriteLock, Redisson supports shared reads and exclusive writes by storing a mode field in the Redis hash to decide whether a lock request can succeed.
10. Multi‑Lock (Batch Lock)
Redisson’s RedissonMultiLock attempts to acquire several locks sequentially; the batch succeeds only if all individual locks are obtained.
11. Problems with Single‑Instance Redis
In master‑slave or Sentinel setups, a lock created on the master may be lost if the master crashes before replication, leading to duplicate locks.
12. RedLock Algorithm
Redisson implements the RedLock algorithm, which acquires the lock on a majority of independent Redis masters (e.g., 3 out of 5). The client records the start time, tries to set the same key with a random value on each node, and considers the lock successful only if it obtains it on a majority within the lock’s TTL.
Example usage:
RLock lock1 = redissonInstance1.getLock("lock1");
RLock lock2 = redissonInstance2.getLock("lock2");
RLock lock3 = redissonInstance3.getLock("lock3");
RedissonRedLock lock = new RedissonRedLock(lock1, lock2, lock3);
lock.lock();
// ...
lock.unlock();The RedLock implementation builds on RedissonMultiLock but only requires a majority of nodes to succeed.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Sanyou's Java Diary
Passionate about technology, though not great at solving problems; eager to share, never tire of learning!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
