Implementation:Apache Shardingsphere EtcdDistributedLock Lock
| Knowledge Sources | |
|---|---|
| Domains | Distributed_Locking, Etcd |
| Last Updated | 2026-02-10 00:00 GMT |
Overview
EtcdDistributedLock implements distributed locking using the etcd Lock and Lease APIs with configurable time-to-live for lock leases.
Description
EtcdDistributedLock implements the DistributedLock interface using the etcd Java client (jetcd). The constructor converts the lock key to a ByteSequence, obtains Lock and Lease clients from the etcd Client, and reads the time-to-live seconds from EtcdProperties. The tryLock method first grants a lease with the configured TTL, then calls lock.lock with the lease ID, waiting up to the specified timeout. If acquisition succeeds, it returns true. InterruptedException restores the interrupt flag and returns false; ExecutionException and TimeoutException also return false. The unlock method calls lock.unlock asynchronously and waits for completion, handling exceptions gracefully.
Usage
This lock implementation is automatically used when etcd is the configured cluster persist repository. It provides distributed mutual exclusion backed by etcd's native lease-based locking, with automatic lock expiration via the TTL.
Code Reference
Source Location
- Repository: Apache_Shardingsphere
- File: EtcdDistributedLock.java
- Lines: 1-75
Signature
public final class EtcdDistributedLock implements DistributedLock {
public EtcdDistributedLock(final String lockKey, final Client client, final EtcdProperties props)
public boolean tryLock(final long timeoutMillis)
public void unlock()
}
Import
import org.apache.shardingsphere.mode.repository.cluster.etcd.lock.EtcdDistributedLock;
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| lockKey | String | Yes | Key path for the distributed lock |
| client | Client | Yes | etcd client providing Lock and Lease clients |
| props | EtcdProperties | Yes | Properties containing TIME_TO_LIVE_SECONDS |
| timeoutMillis | long | Yes | Maximum time to wait for lock acquisition |
Outputs
| Name | Type | Description |
|---|---|---|
| isLocked | boolean | Whether the lock was acquired within the timeout |
Usage Examples
EtcdDistributedLock lock = new EtcdDistributedLock("/locks/config_change", etcdClient, etcdProps);
if (lock.tryLock(5000L)) {
try {
// Lock acquired with a lease TTL; auto-expires if holder crashes
performExclusiveOperation();
} finally {
lock.unlock();
}
}