Mastering Distributed Locks: Redis, Redisson, and ZooKeeper Implementations

This article explains the concepts and practical implementations of distributed locks using Redis, Redisson, and ZooKeeper, covering lock acquisition, expiration handling, atomicity, automatic renewal, and code examples for Java developers working in clustered environments.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Mastering Distributed Locks: Redis, Redisson, and ZooKeeper Implementations

Locks like Synchronized and ReentrantLock work for single‑process threads, but in clustered deployments a distributed lock is needed.

In a distributed lock all services contend for a single lock entry; only the holder proceeds.

Redis implementation

Redis provides SETNX (set if not exists) to acquire a lock. To avoid deadlock when a process crashes, an expiration time must be set atomically. Since Redis 2.8 the combined command SET key value EX seconds NX does this.

When the lock expires while the business logic is still running, a new lock may be created and the old holder could mistakenly release it. Therefore a random token is stored with the lock and compared before deletion.

private static final String LOCK_SUCCESS = "OK";
private static final Long RELEASE_SUCCESS = 1L;
private static final String SET_IF_NOT_EXIST = "NX";
private static final String SET_WITH_EXPIRE_TIME = "PX";

@Override
public String acquire() {
    try {
        long end = System.currentTimeMillis() + acquireTimeout;
        String requireToken = UUID.randomUUID().toString();
        while (System.currentTimeMillis() < end) {
            String result = jedis.set(lockKey, requireToken,
                    SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime);
            if (LOCK_SUCCESS.equals(result)) {
                return requireToken;
            }
            try { Thread.sleep(100); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
        }
    } catch (Exception e) {
        log.error("acquire lock due to error", e);
    }
    return null;
}

@Override
public boolean release(String identify) {
    if (identify == null) return false;
    String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
    Object result = null;
    try {
        result = jedis.eval(script, Collections.singletonList(lockKey),
                Collections.singletonList(identify));
        if (RELEASE_SUCCESS.equals(result)) {
            log.info("release lock success, requestToken:{}", identify);
            return true;
        }
    } catch (Exception e) {
        log.error("release lock due to error", e);
    } finally {
        if (jedis != null) jedis.close();
    }
    log.info("release lock failed, requestToken:{}, result:{}", identify, result);
    return false;
}

Redisson implementation

Redisson wraps Redis and offers distributed Java objects. Adding the Maven dependency and calling

RLock lock = redissonClient.getLock("test_lock"); lock.lock(); ... lock.unlock();

provides a simple API similar to ReentrantLock. It supports read‑write locks, fair locks, and RedLock.

Redisson automatically renews the lock (default 30 s) while the holder is alive; if the business thread finishes, the lock is released manually or expires after the timeout, preventing deadlock.

private void test() {
    RLock lock = redissonClient.getLock("test_lock");
    lock.lock();
    try {
        // business logic
    } finally {
        lock.unlock();
    }
}

ZooKeeper implementation

ZooKeeper can also serve as a coordination service for distributed locks by creating temporary sequential nodes. The smallest node holds the lock; others set a watcher on the predecessor node. When the lock node is deleted, the next node acquires the lock.

This approach avoids the “herd effect” of non‑sequential nodes and automatically cleans up locks if the client crashes, because temporary nodes disappear.

public class ZooKeeperDistributedLock implements Watcher {
    private ZooKeeper zk;
    private String locksRoot = "/locks";
    private String productId;
    private String waitNode;
    private String lockNode;
    private CountDownLatch latch;
    private CountDownLatch connectedLatch = new CountDownLatch(1);
    private int sessionTimeout = 30000;

    public ZooKeeperDistributedLock(String productId) { /* ... */ }

    public void process(WatchedEvent event) { /* ... */ }

    public void acquireDistributedLock() { /* ... */ }

    public boolean tryLock() { /* ... */ }

    private boolean waitForLock(String waitNode, long waitTime) throws InterruptedException, KeeperException { /* ... */ }

    public void unlock() { /* ... */ }

    public static class LockException extends RuntimeException { /* ... */ }
}

Summary

Redis uses a key‑value entry with expiration; ZooKeeper uses a temporary sequential node.

On crash, Redis relies on TTL, while ZooKeeper removes the temporary node automatically.

Redis typically spins to acquire a lock; ZooKeeper uses watchers, offering better performance under contention.

Choose the implementation that fits your stack and latency requirements.

Original link: https://juejin.cn/post/6891571079702118407

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.

JavaconcurrencyredisZooKeeperdistributed-lockredisson
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

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.