Implementation:Apache Shardingsphere DistributedLock SPI
| Knowledge Sources | |
|---|---|
| Domains | SPI, Distributed_Locking |
| Last Updated | 2026-02-10 00:00 GMT |
Overview
DistributedLock is the SPI interface for distributed locking, defining tryLock and unlock operations for exclusive access across cluster nodes.
Description
DistributedLock is a minimal interface with two methods: tryLock attempts to acquire the lock within a specified timeout in milliseconds and returns a boolean indicating success, and unlock releases the lock. Implementations include DefaultDistributedLock (backed by ClusterPersistRepository with reentrant thread-local tracking), EtcdDistributedLock (using etcd Lock and Lease APIs), and ZookeeperDistributedLock (wrapping Curator's InterProcessMutex). The interface enables exclusive operations such as statistics collection and configuration changes in cluster mode.
Usage
Use this interface when implementing or consuming distributed lock behavior in cluster mode. Locks are typically obtained from the ClusterPersistRepository lock provider and used to guard exclusive operations that must not run concurrently across cluster nodes.
Code Reference
Source Location
- Repository: Apache_Shardingsphere
- File: DistributedLock.java
- Lines: 1-37
Signature
public interface DistributedLock {
boolean tryLock(long timeoutMillis);
void unlock();
}
Import
import org.apache.shardingsphere.mode.repository.cluster.lock.DistributedLock;
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| timeoutMillis | long | Yes | Maximum time to wait for lock acquisition in milliseconds |
Outputs
| Name | Type | Description |
|---|---|---|
| isLocked | boolean | Whether the lock was successfully acquired within the timeout |
Usage Examples
DistributedLock lock = clusterPersistRepository.getDistributedLock("/locks/statistics_refresh");
if (lock.tryLock(5000L)) {
try {
// Perform exclusive operation
refreshStatistics();
} finally {
lock.unlock();
}
}