Implementing Distributed Locks with Redis and Redisson

This article explains how to create Redis‑based distributed locks, discusses common pitfalls such as deadlocks and accidental deletions, and provides practical solutions including atomic expiration commands, Lua scripts, and a complete Redisson Java example for acquiring and releasing locks safely.

Selected Java Interview Questions
Selected Java Interview Questions
Selected Java Interview Questions
Implementing Distributed Locks with Redis and Redisson

Redis can serve as a distributed system, making it suitable for implementing distributed locks. The simplest approach uses the SETNX command to acquire a lock and DEL to release it, checking the command's return value to confirm success.

The basic Redis lock suffers from two major issues: (1) deadlock when the lock is created without an expiration time, and (2) accidental deletion when a lock expires while a client is still processing, causing another client to delete a lock it does not own.

To solve the deadlock problem, Redis 2.6.12 introduced the ability to set an expiration atomically with the lock acquisition, for example using SET key value NX EX 30 (or a combination of SETNX followed by EXPIRE).

To avoid lock‑deletion errors, a lock identifier (e.g., the thread ID) can be stored as the value, and the lock release must verify ownership before deletion. Because this two‑step check is not atomic, the recommended solution is to use a Lua script that performs the check‑and‑delete in a single operation, or to rely on a higher‑level library such as Redisson.

Below is a complete Redisson example.

1. Add the Redisson dependency:

<dependency>
    <groupId>org.redisson</groupId>
    <artifactId>redisson-spring-boot-starter</artifactId>
    <version>3.23.2</version>
</dependency>

2. Configure a RedissonClient bean:

@Configuration
public class RedissonConfig {
    @Bean
    public RedissonClient redissonClient() {
        Config config = new Config();
        config.useSingleServer().setAddress("redis://127.0.0.1:6379");
        // If a password is required, set it here
        return Redisson.create(config);
    }
}

3. Use the client to acquire and release a lock:

@RestController
public class LockController {
    @Resource
    private RedissonClient redissonClient;

    @RequestMapping("/lock")
    public String lockResource() throws InterruptedException {
        String lockKey = "myLock";
        RLock lock = redissonClient.getLock(lockKey);
        try {
            // Try to acquire the lock for up to 20 seconds, hold it for 10 seconds
            boolean isLocked = lock.tryLock(20, TimeUnit.SECONDS);
            if (isLocked) {
                try {
                    TimeUnit.SECONDS.sleep(5);
                    return "Successfully acquired lock and executed business logic";
                } finally {
                    lock.unlock(); // Release the lock
                }
            } else {
                return "Failed to acquire lock";
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "Lock acquisition completed";
    }
}

After starting the Spring Boot application, access http://localhost:8080/lock to test the distributed lock implementation.

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-lockredisson
Selected Java Interview Questions
Written by

Selected Java Interview Questions

A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!

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.