Why Redisson’s Reentrant Distributed Lock Relies on HINCRBY Increment and Decrement
The article explains how Redisson implements a re‑entrant distributed lock using Redis hash structures and the atomic HINCRBY command to manage client identity, re‑entry counting, concurrency safety, and graceful release, providing a complete technical analysis with code, Lua scripts, and best‑practice guidelines.
Background
In distributed systems, multiple service instances need to synchronize access to shared resources. Traditional JVM locks (synchronized, ReentrantLock) cannot work across processes, so a distributed lock is required.
Why Redisson uses HINCRBY
Redisson implements a reentrant lock (RLock) by storing lock state in a Redis hash. Each field is a unique client/thread identifier (e.g., UUID:threadId) and the value is the re‑entry count. HINCRBY atomically increments or decrements this count, providing both identity isolation and atomicity.
Four challenges of distributed locks
Client identity recognition
Reentrant count management
Concurrent safety
Graceful release
HINCRBY in each challenge
Identity: the hash field isolates threads.
Reentrancy: the field value stores the count; HINCRBY +1 on lock, ‑1 on unlock.
Atomicity: Redis’s single‑threaded execution guarantees no race conditions.
Release: when the count reaches zero, the key is deleted.
Lock acquisition flow
private CompletableFuture<Long> tryAcquireOnceAsync(...){
// Lua script (simplified):
// if key does not exist -> HINCRBY field 1, set TTL
// else if field exists -> HINCRBY field 1, refresh TTL
// else return PTTL (remaining TTL)
}The script creates the hash and sets the count to 1 for a new lock, increments the count for re‑entry, and returns the remaining TTL when another client holds the lock.
Unlock flow
protected CompletableFuture<Void> unlockInnerAsync(...){
// Lua script (simplified):
// if field not present -> return nil
// counter = HINCRBY field -1
// if counter > 0 -> refresh TTL
// else DEL key (full release)
}Only the owning client can decrement the counter; the lock is fully released only when the counter reaches zero.
Alternative approaches
GET‑INCR‑SET (non‑atomic, leads to race conditions)
Simple INCR on a string key (cannot distinguish threads)
Multiple keys per thread (high memory, hard cleanup)
WATCH‑MULTI‑EXEC (optimistic lock, performance penalty)
All alternatives either break atomicity or lose thread isolation, making HINCRBY the optimal choice.
Core API example
Config config = new Config();
config.useSingleServer().setAddress("redis://127.0.0.1:6379");
RedissonClient redisson = Redisson.create(config);
RLock lock = redisson.getLock("mylock");
if (lock.tryLock(10, 30, TimeUnit.SECONDS)) {
try {
// business logic
anotherMethod(lock); // re‑entrant call
} finally {
lock.unlock(); // triggers HINCRBY -1
}
}Best practices
Never use a permanent lock; always set a lease time.
Prefer tryLock(waitTime, leaseTime, unit) to control both wait and expiry.
Set the lease time slightly larger than the expected business execution time.
Use Redisson’s watchdog only when lease time is omitted.
Always match lock and unlock calls; mismatched calls raise IllegalMonitorStateException.
Monitor lock contention with HGETALL and PTTL or external APM tools.
Philosophical insight
HINCRBYacts as a “state decision entry” that simultaneously answers three questions: does the lock exist, does it belong to the caller, and how should the state be updated. This atomic “read‑judge‑write” pattern is the cornerstone of safe re‑entrant distributed locking.
Using HINCRBY for both increment and decrement is not a gimmick; it is the minimal, reliable solution that satisfies identity isolation and atomic state transition in a high‑concurrency environment.
Core flow diagram
Tech Freedom Circle
Crazy Maker Circle (Tech Freedom Architecture Circle): a community of tech enthusiasts, experts, and high‑performance fans. Many top‑level masters, architects, and hobbyists have achieved tech freedom; another wave of go‑getters are hustling hard toward tech freedom.
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.
