Implementing Distributed Locks with Redis and Redisson Watchdog Mechanism
This article explains how to implement a distributed lock using Redis by setting a unique key-value pair, handling expiration, addressing lock timeout issues, and leveraging Redisson's watchdog mechanism with automatic renewal, including detailed code examples for tryLock, subscription, and renewal processes.
Redis can be used to implement a distributed lock by storing a unique key as the lock marker and a unique client identifier as its value. The lock is set only when the key does not exist, ensuring mutual exclusion, and an expiration time prevents deadlocks.
The article discusses the problem when the lock expiration (e.g., 30 seconds) is shorter than the business processing time, leading to lock loss and potential contention, and outlines the trade‑offs of setting the lock timeout too short or too long.
One solution is automatic renewal: a watchdog thread periodically extends the lock’s TTL before it expires. Redisson provides such a watchdog mechanism.
Redisson’s public boolean tryLock(long waitTime, long leaseTime, TimeUnit unit) throws InterruptedException { ... } method is shown, illustrating how it attempts to acquire the lock, subscribes to lock‑release events, waits with a semaphore, and retries within the configured wait time.
The watchdog implementation is explained: after a lock is acquired, Redisson registers the owning thread in RedissonLock.EXPIRATION_RENEWAL_MAP and a background task checks every internalLockLeaseTime / 3 (≈10 seconds) to extend the key’s TTL using a Lua script if the thread still holds the lock.
If the client crashes, the watchdog thread stops, the lock expires after the default 30 seconds, and other clients can acquire it.
The article also includes promotional material for a technical learning group, which is not part of the technical explanation.
Architecture Digest
Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.
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.