Backend Development 21 min read

Understanding Redis Distributed Locks: Features, Implementations, and Best Practices

This article explains why distributed locks are needed, describes the five essential characteristics of Redis locks, compares three common implementation methods, and provides detailed Java code examples with watchdog, re‑entrancy, and expiration handling to guide developers in building reliable distributed locking solutions.

JD Tech
JD Tech
JD Tech
Understanding Redis Distributed Locks: Features, Implementations, and Best Practices

The article begins by asking why distributed locks are necessary, highlighting that in multi‑service, multi‑node environments a single JVM lock is insufficient and a mediator is required to ensure only one thread across all processes holds the lock at any time.

It then outlines the five key properties of a good distributed lock: mutual exclusion, dead‑lock avoidance, owner‑only unlock ("the one who rings the bell must untie it"), re‑entrancy, and fault tolerance.

Three typical implementation approaches are listed: database lock, ZooKeeper‑based lock, and Redis‑based lock.

For Redis locks, the article provides concrete Java examples. The basic usage shows acquiring a lock, executing business logic, and releasing the lock:

public static void doSomething() {
    RedisLock redisLock = new RedisLock(jedis);
    try {
        redisLock.lock(); // acquire lock
        // business logic
        System.out.println(Thread.currentThread().getName() + " thread processing...");
        Thread.sleep(2000);
        System.out.println(Thread.currentThread().getName() + " thread done");
        redisLock.unlock(); // release lock
    } catch (Exception e) {
        e.printStackTrace();
    }
}

It emphasizes that unlocking must be placed in a finally block to guarantee release even when exceptions occur.

The article discusses setting an expiration time (watchdog) to avoid permanent lockouts when a process crashes, using Redis SET key value EX seconds NX for atomic lock creation:

SetParams setParams = new SetParams();
setParams.ex(1); // 1 second TTL
setParams.nx();
String response = jedis.set(lock_key, "", setParams);
return "OK".equals(response);

To ensure only the lock owner can release the lock, a unique token (UUID or APP_ID+ThreadId) is stored as the lock value, and a Lua script atomically checks the token before deletion:

String releaseLock_lua = "if redis.call(\"get\", KEYS[1]) == ARGV[1] then\n" +
        "    return redis.call(\"del\", KEYS[1])\n" +
        "else\n" +
        "    return 0\n" +
        "end";

Re‑entrancy is achieved by checking if the current thread already holds the lock (using the stored token) and, if so, simply returning without acquiring a new lock.

For distributed environments where thread IDs may collide across JVMs, the article proposes combining a globally unique application identifier (APP_ID) with the thread ID as the lock token.

It also covers handling lock renewal (watchdog) with a scheduled task that periodically extends the lock’s TTL only if the current process still owns the lock, using another Lua script:

private String threadAddLife_lua = "if redis.call(\"exists\", KEYS[1]) == 1 then\n" +
        "    return redis.call(\"expire\", KEYS[1], ARGV[1])\n" +
        "else\n" +
        "    return 0\n" +
        "end";

Finally, the article mentions monitoring and fallback strategies for cases where a node crashes and the lock remains until its TTL expires, suggesting external health checks to forcibly delete stale locks.

In conclusion, understanding these five characteristics and applying the presented code patterns helps developers implement robust Redis‑based distributed locks without over‑locking or risking deadlocks.

JavaConcurrencyRedisDistributed LockLuawatchdog
JD Tech
Written by

JD Tech

Official JD technology sharing platform. All the cutting‑edge JD tech, innovative insights, and open‑source solutions you’re looking for, all in one place.

0 followers
Reader feedback

How this landed with the community

login 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.