Understanding and Implementing Redis Distributed Locks

This article explains the concept, necessity, key characteristics, and step‑by‑step Java implementation of Redis‑based distributed locks, providing code examples and guidance for ensuring mutual exclusion, reliability, and performance in backend systems.

Mike Chen's Internet Architecture
Mike Chen's Internet Architecture
Mike Chen's Internet Architecture
Understanding and Implementing Redis Distributed Locks

Distributed Lock

Distributed lock is a mechanism that ensures mutual exclusion when multiple nodes or processes access shared resources in a distributed system.

Why Distributed Locks Are Needed

Without proper locking, concurrent access can cause data inconsistency or conflicts, such as three JBoss instances needing exclusive access to a resource.

Redis or ZooKeeper can be used to implement distributed locks.

Characteristics of Distributed Locks

They must provide mutual exclusion, reliability, performance, and re‑entrancy.

Mutual Exclusion : Only one client can hold the lock at any time.

Reliability : The lock should remain correct under network partitions, node failures, or client crashes, and be released automatically if the holder fails.

Performance : Low latency and high throughput to avoid becoming a bottleneck.

Redis Distributed Lock Implementation

1. Acquire Lock

The client attempts to set a specific key with SETNX; success means the lock is acquired.

boolean success = redis.setnx(lockKey, uniqueId);

2. Set Expiration

An expiration time prevents deadlocks. redis.expire(lockKey, expireTime); 3. Release Lock

The lock is released only by its owner.

void releaseLock(String lockKey, String uniqueId) {
    String currentLockValue = redis.get(lockKey);
    if (currentLockValue != null && currentLockValue.equals(uniqueId)) {
        redis.del(lockKey);
    }
}

Complete Java example:

import redis.clients.jedis.Jedis;

public class RedisDistributedLock {
    private static final String LOCK_KEY = "resource_lock";
    private static final String CLIENT_ID = "unique_id";
    private static final int EXPIRE_TIME = 60; // seconds

    private Jedis jedis;

    public RedisDistributedLock() {
        jedis = new Jedis("localhost");
    }

    public boolean acquireLock() {
        Long setResult = jedis.setnx(LOCK_KEY, CLIENT_ID);
        if (setResult == 1) {
            jedis.expire(LOCK_KEY, EXPIRE_TIME);
            return true;
        }
        return false;
    }

    public void releaseLock() {
        String currentLockValue = jedis.get(LOCK_KEY);
        if (currentLockValue != null && currentLockValue.equals(CLIENT_ID)) {
            jedis.del(LOCK_KEY);
        }
    }

    public static void main(String[] args) {
        RedisDistributedLock lock = new RedisDistributedLock();
        try {
            if (lock.acquireLock()) {
                System.out.println("Lock acquired successfully");
                // Do something...
            } else {
                System.out.println("Failed to acquire lock");
            }
        } finally {
            lock.releaseLock();
        }
    }
}

The article also offers a free collection of architecture and interview materials for readers.

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.

BackendJavaredisdistributed-lock
Mike Chen's Internet Architecture
Written by

Mike Chen's Internet Architecture

Over ten years of BAT architecture experience, shared generously!

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.