Distributed Locks: Concepts, Characteristics, and Implementation Strategies (Redis, ZooKeeper, Redisson)
This article explains the definition of distributed locks, the challenges of mutual exclusion in distributed environments, and compares four implementation approaches—plain Redis, ZooKeeper, and Redisson—detailing their mechanisms, advantages, drawbacks, and practical code examples.
0. Definition A distributed lock is a lock that works across multiple nodes in a distributed system, ensuring mutual exclusion for shared resources.
1. Problem Introduction When multiple services concurrently modify a shared value (e.g., incrementing or decrementing a counter), race conditions can produce incorrect results. Locks are the primary tool to enforce exclusive access.
2. Characteristics of Distributed Environments Key traits include horizontal scalability, high reliability, high concurrency, and cost‑effective use of many small machines.
3. Locks in Single‑Process/Thread Contexts Traditional mutexes exist in multithreaded languages (e.g., sync.Mutex in Go, ReentrantLock in Java) and inter‑process mechanisms such as semaphores.
4. Need for Distributed Locks In a distributed deployment, services must coordinate to avoid duplicate work, ensure correctness of shared data, and maintain high efficiency.
5. Distributed Lock Implementation Schemes
5.1 Plain Redis
Four variants are discussed:
• Scheme 1: setnx + delete
1 setnx lock_key lock_value
2 // do sth
3 delete lock_keyDrawback: if the client crashes after acquiring the lock, the lock remains forever (deadlock).
• Scheme 2: setnx + setex
1 setnx lock_key lock_value
2 setex lock_key N lock_value // N seconds timeout
3 // do sth
4 delete lock_keyStill non‑atomic; a crash between the two commands can cause deadlock.
• Scheme 3: SET … EX NX (atomic)
1 SET lock_key lock_value EX N NX // N seconds timeout
2 // do sth
3 delete lock_keyThis combines acquisition and expiration in a single atomic command (Redis ≥2.6.12) and is widely used.
• Scheme 4: Lua script for safe release
1 if redis.call("get",KEYS[1]) == ARGV[1] then
2 return redis.call("del",KEYS[1])
3 else
4 return 0
5 endEnsures only the owner can delete the lock; typically used together with Scheme 3.
5.2 ZooKeeper
ZooKeeper provides a coordination service with strong consistency. Locks are implemented using EPHEMERAL nodes and watches. A client creates an EPHEMERAL_SEQUENTIAL node under a lock path; the smallest sequence number wins the lock. Other clients watch the predecessor node to avoid herd effect.
Dependency (Maven):
1 <dependency>
2 <groupId>org.apache.curator</groupId>
3 <artifactId>curator-recipes</artifactId>
4 <version>2.11.1</version>
5 </dependency>Sample Java code using Curator:
public class TestLock {
public static void main(String[] args) throws Exception {
// create ZK client
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
CuratorFramework client = CuratorFrameworkFactory.newClient("ip:port", retryPolicy);
client.start();
// create distributed lock at /sunnyzengqi/curator/lock
InterProcessMutex mutex = new InterProcessMutex(client, "/sunnyzengqi/curator/lock");
mutex.acquire();
// business logic
System.out.println("Enter mutex");
Thread.sleep(10000);
// release lock
mutex.release();
client.close();
}
}5.3 Redisson
Redisson is a Java client for Redis that offers high‑level distributed objects, including re‑entrant, fair, and read‑write locks. It uses a watchdog thread to automatically extend lock TTL, avoiding deadlocks caused by client crashes.
6. Summary Redis‑based locks are simple and language‑agnostic, ZooKeeper offers strong consistency and watch‑based notifications, while Redisson provides rich lock types but is Java‑specific. Choice depends on ecosystem, required lock features, and operational constraints.
7. Conclusion Distributed locks are essential for correct concurrent operations in modern micro‑service architectures; understanding their trade‑offs helps engineers design robust, high‑performance systems.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Architecture Digest
Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
