Skip to content

Home

Redlock4j logo

CI codecov Maven Central Javadocs Java Guide

A robust Java implementation of the Redlock distributed locking algorithm for Redis.

Overview

Redlock4j provides a reliable distributed locking mechanism using Redis, implementing the Redlock algorithm proposed by Redis creator Antirez. It ensures mutual exclusion across distributed systems with high availability and fault tolerance.

Key Features

Quick Example

import org.codarama.redlock4j.RedlockManager;
import org.codarama.redlock4j.configuration.RedlockConfiguration;

import java.time.Duration;
import java.util.concurrent.locks.Lock;

// Configure the Redis nodes (host/port) and lock behaviour
RedlockConfiguration config = RedlockConfiguration.builder()
    .addRedisNode("redis1.example.com", 6379)
    .addRedisNode("redis2.example.com", 6379)
    .addRedisNode("redis3.example.com", 6379)
    .defaultLockTimeout(Duration.ofSeconds(30))
    .retryDelay(Duration.ofMillis(200))
    .maxRetryAttempts(3)
    .build();

// RedlockManager is AutoCloseable - use try-with-resources
try (RedlockManager manager = RedlockManager.withJedis(config)) {
    Lock lock = manager.createLock("my-resource");
    lock.lock();
    try {
        // Critical section - your protected code here
        performCriticalOperation();
    } finally {
        // Always unlock in a finally block
        lock.unlock();
    }
}

Why Redlock4j?

Distributed Lock Guarantees

Redlock4j provides the following safety and liveness guarantees:

  1. Mutual Exclusion - At most one client can hold a lock at any given time
  2. Deadlock Free - Eventually it's always possible to acquire a lock, even if the client that locked a resource crashes
  3. Fault Tolerance - As long as the majority of Redis nodes are up, clients can acquire and release locks

Use Cases

  • Distributed Task Scheduling - Ensure only one instance processes a scheduled task
  • Resource Access Control - Coordinate access to shared resources across services
  • Leader Election - Implement leader election in distributed systems
  • Rate Limiting - Implement distributed rate limiting
  • Cache Invalidation - Coordinate cache updates across multiple instances

Getting Started

Check out the Installation Guide to add Redlock4j to your project, or jump straight to the Quick Start to see it in action.

License

Redlock4j is released under the MIT License.