NOTE
1.2 How to Implement Distributed Locks
Distributed locks coordinate resource access across processes or machines. These notes compare implementations starting from requirements such as atomic lock and unlock operations.
This is a historical learning note and may contain outdated or incomplete understanding.
1. What Is a Distributed Lock?
A lock in a distributed environment (across processes or machines).
It satisfies the following conditions:
- Atomicity
Lock acquisition and release must be atomic.
- Mutual exclusion
At any moment, only one client can hold the lock.
- No deadlock
Even if a client crashes while holding the lock without explicitly releasing it, other clients must still be able to acquire the lock afterward.
- A lock must be acquired and released by the same client.
A lock must be acquired and released by the same client. A client cannot release a lock acquired by someone else.
For example, in this scenario, A acquires the lock with an expiration time of 10 seconds, but A actually runs for 15 seconds, so the lock is automatically released. Then B successfully acquires the lock. At the 15th second, A finishes execution and releases the lock. Here, A has released the lock acquired by B.
2. Why Are Distributed Locks Needed?
Built-in locks in various languages, such as Java’s synchronized and Go’s mutex, can only guarantee lock properties within a single process and cannot span processes or machines.
3. How to Implement Distributed Locks
3.1. ZooKeeper
3.2. Redis
3.3. ZooKeeper vs Redis
| Redis | ZooKeeper | |
|---|---|---|
| Lock acquisition fails | Needs continuous active polling | Register a listener and wait for a callback |
| Client holding the lock crashes | Must wait until the timeout expires before acquiring the lock again | The ephemeral node automatically releases the lock |
| Performance | High | Low |
4. References
Drag to pan, scroll to zoom, and click a node to expand or collapse it. Large maps start with deeper levels collapsed; click nodes to expand them.
Discussion
Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub