How Redisson Implements Distributed Locks with Redis: A Deep Dive into Lua Scripts and Watchdog

This article explains how Redisson provides Redis‑based distributed locks, covering atomic lock acquisition via Lua scripts, lease time handling, watchdog auto‑extension, re‑entrant and fair locks, read‑write locks, multi‑lock batching, and the RedLock algorithm for high‑availability scenarios.

Su San Talks Tech
Su San Talks Tech
Su San Talks Tech
How Redisson Implements Distributed Locks with Redis: A Deep Dive into Lua Scripts and Watchdog

Why Use Distributed Locks in a Distributed System

When multiple service instances need to lock the same resource, traditional single‑process locks such as synchronized or ReentrantLock are insufficient, so a distributed lock is required. Common implementations include ZooKeeper and Redis, with Redis being popular for its simplicity.

Redisson as a Redis Distributed Lock Provider

Redisson is a well‑known library that implements distributed locks on top of Redis. The article focuses on how Redisson achieves lock atomicity, lease handling, re‑entrancy, fairness, read‑write semantics, batch locking, and the RedLock algorithm.

1. Ensuring Atomicity of Lock Acquisition

Redisson does not rely on the SETNX command directly. Instead, it implements its own locking logic that ultimately executes a Lua script in Redis, guaranteeing atomicity.

Lock acquisition starts by obtaining an RLock from a RedissonClient using the lock name. The lock() method eventually calls an overloaded version with leaseTime = -1, which then invokes tryAcquire and tryAcquireAsync.

The asynchronous method ultimately calls tryLockInnerAsync, which runs a Lua script to perform the lock. If leaseTime is -1, Redisson uses a default internal lease time of 30 seconds.

2. Implementing Lock with a Lua Script

The Lua script receives three arguments:

KEYS[1] : the lock name (e.g., myLock)

ARGV[1] : lock expiration time (default 30 s if not specified)

ARGV[2] : a unique identifier composed of a client UUID and thread ID

The script first checks EXISTS to see if the key is present. If not, it uses HINCRBY to store the identifier with a count of 1, establishing a re‑entrant lock count, and then sets the expiration with PEXPIRE.

3. Why Set an Expiration Time

Setting a lease time prevents deadlocks: if a client crashes before releasing the lock, the key will eventually expire, allowing other threads to acquire it.

4. Automatic Lease Extension (Watchdog)

If no lease time is specified, Redisson starts a watchdog thread that periodically (default every 10 seconds) runs another Lua script to extend the lock’s expiration, ensuring the lock remains valid while the owning thread is alive.

5. Re‑entrant Locking

When the same client thread attempts to lock again, the Lua script detects the existing identifier and increments the lock count instead of creating a new lock.

6. Unlocking Safely

Unlocking is performed via unlock(), which calls unlockAsync and ultimately runs a Lua script that verifies the releasing thread matches the lock owner, decrements the count, and deletes the key when the count reaches zero.

7. Automatic Expiration (Timeout Release)

When a lease time is provided (e.g., lock(long leaseTime, TimeUnit unit)), Redisson does not start the watchdog; the key simply expires after the specified duration.

void lock(long leaseTime, TimeUnit unit)

8. Blocking Until Lock Acquired

If a lock attempt fails, Redisson enters a spin‑loop that repeatedly calls tryAcquire until success, effectively blocking the thread.

9. Timed Blocking (Give‑up After Wait)

Methods such as tryLock(long waitTime, long leaseTime, TimeUnit unit) allow specifying a maximum wait time, after which the attempt is abandoned.

boolean tryLock(long waitTime, long leaseTime, TimeUnit unit)
boolean tryLock(long time, TimeUnit unit)

10. Fair Locks

Redisson provides a fair lock via getFairLock, implemented in RedissonFairLock. It maintains a queue (a Redis set) to ensure lock acquisition follows request order.

11. Read‑Write Locks

RedissonReadWriteLock enables concurrent reads while writes remain exclusive. It stores a mode field in a Redis hash to distinguish read versus write mode and enforce the appropriate semantics.

12. Batch (Multi) Locking

RedissonMultiLock allows acquiring several locks atomically; all must succeed for the batch lock to be considered acquired.

13. RedLock Algorithm for High Availability

In a Redis cluster without replication, RedLock acquires the lock on a majority of nodes (N/2 + 1). The client records the start time, attempts to set the lock on each node with a short network timeout, and succeeds only if the majority acknowledges within the lock’s TTL. If it fails, the client releases any partial locks.

RLock lock1 = redissonInstance1.getLock("lock1");
RLock lock2 = redissonInstance2.getLock("lock2");
RLock lock3 = redissonInstance3.getLock("lock3");
RedissonRedLock lock = new RedissonRedLock(lock1, lock2, lock3);
lock.lock(); // acquire on majority
... // business logic
lock.unlock();

Conclusion

Redisson offers a comprehensive suite of distributed locking primitives—simple locks, re‑entrant locks, fair locks, read‑write locks, multi‑locks, and the RedLock algorithm—each built on atomic Lua scripts and optional watchdog extensions to balance safety and performance in distributed Java applications.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

redisread-write lockredissonLua ScriptWatchdogfair lock
Su San Talks Tech
Written by

Su San Talks Tech

Su San, former staff at several leading tech companies, is a top creator on Juejin and a premium creator on CSDN, and runs the free coding practice site www.susan.net.cn.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.