Class OpenLock
Provides unified API for creating and managing various types of locks.
提供创建和管理各种类型锁的统一API。
Features | 主要功能:
- Local reentrant locks - 本地可重入锁
- Read-write locks - 读写锁
- Spin locks for short critical sections - 短临界区自旋锁
- Segment locks for fine-grained locking - 细粒度分段锁
- Stamped locks with optimistic reads - 支持乐观读的戳记锁
- Retry locks with exponential backoff - 指数退避重试锁
- TTL locks with auto-expiry - 带自动过期的TTL锁
- Observable locks with event listeners - 带事件监听的可观察锁
- Lock groups with deadlock prevention - 带死锁预防的锁组
- Named lock factory with striping - 带条纹的命名锁工厂
Usage Examples | 使用示例:
// Create a local lock | 创建本地锁
Lock<Long> lock = OpenLock.lock();
// Execute with lock | 使用锁执行
lock.execute(() -> {
// Critical section | 临界区
});
// Create read-write lock | 创建读写锁
ReadWriteLock<Long> rwLock = OpenLock.readWriteLock();
rwLock.executeRead(() -> loadData());
rwLock.executeWrite(() -> saveData());
// Create spin lock for short critical sections | 为短临界区创建自旋锁
Lock<Long> spinLock = OpenLock.spinLock();
// Create segment lock for key-based locking | 为基于键的锁定创建分段锁
SegmentLock<String> segmentLock = OpenLock.segmentLock(32);
segmentLock.execute("user:123", () -> updateUser("123"));
// Create named lock factory | 创建命名锁工厂
NamedLockFactory factory = OpenLock.namedLockFactory();
factory.execute("order:12345", () -> processOrder("12345"));
// Create lock group (deadlock prevention) | 创建锁组(死锁预防)
try (var guard = OpenLock.lockGroup()
.add(lockA).add(lockB)
.build().lockAll()) {
transferFunds(accountA, accountB);
}
Security | 安全性:
- Thread-safe: Yes - 线程安全: 是
- Virtual Thread friendly: Yes - 虚拟线程友好: 是
- Since:
- JDK 25, opencode-base-lock V1.0.0
- Author:
- Leon Soo www.LeonSoo.com
- See Also:
-
Method Summary
Modifier and TypeMethodDescriptionstatic LockConfig.BuilderCreates a lock configuration builder 创建锁配置构建器static LockConfigGets default lock configuration 获取默认锁配置static DistributedLockConfigGets default distributed lock configuration 获取默认分布式锁配置Creates a distributed lock configuration builder 创建分布式锁配置构建器static voidExecutes action with a new temporary lock 使用新的临时锁执行操作static <R> RexecuteWithResult(Supplier<R> supplier) Executes supplier with a new temporary lock and returns result 使用新的临时锁执行并返回结果fairLock()Creates a fair lock that grants access in FIFO order 创建按FIFO顺序授予访问权限的公平锁lock()Creates a local reentrant lock with default configuration 使用默认配置创建本地可重入锁lock(LockConfig config) Creates a local lock with specified configuration 使用指定配置创建本地锁static LockGroup.BuilderCreates a lock group builder for atomic multi-lock acquisition 创建用于原子多锁获取的锁组构建器static LockManagermanager()Gets the default singleton lock manager 获取默认单例锁管理器static LockManagermanager(LockConfig config) Creates a new lock manager with specified configuration 使用指定配置创建新的锁管理器static NamedLockFactoryCreates a named lock factory with default settings 使用默认设置创建命名锁工厂static NamedLockFactorynamedLockFactory(int stripes) Creates a named lock factory with specified stripe count 使用指定条纹数创建命名锁工厂static <T> Lock<T> observableLock(Lock<T> delegate, String lockName, LockListener... listeners) Wraps an existing lock with event observation 用事件观察包装现有锁observableLock(String lockName, LockListener... listeners) Creates an observable lock that fires events to listeners 创建向监听器触发事件的可观察锁static ReadWriteLock<Long> Creates a read-write lock allowing concurrent readers 创建允许并发读取的读写锁static ReadWriteLock<Long> readWriteLock(LockConfig config) Creates a read-write lock with specified configuration 使用指定配置创建读写锁Creates a retry lock wrapping a new local lock with default retry settings 使用默认重试设置包装新本地锁创建重试锁static <T> RetryLock.Builder<T> Creates a retry lock builder wrapping the specified lock 创建包装指定锁的重试锁构建器static <K> SegmentLock<K> Creates a segment lock with default 16 segments 使用默认16个分段创建分段锁static <K> SegmentLock<K> segmentLock(int segments) Creates a segment lock with specified number of segments 使用指定分段数创建分段锁spinLock()Creates a spin lock for very short critical sections 为极短临界区创建自旋锁spinLock(int maxSpinCount) Creates a spin lock with custom max spin count 使用自定义最大自旋次数创建自旋锁static StampedLockAdapterCreates a stamped lock adapter with optimistic read support 创建支持乐观读的戳记锁适配器static StampedLockAdapterstampedLock(LockConfig config) Creates a stamped lock adapter with specified configuration 使用指定配置创建戳记锁适配器Creates a lock with TTL (Time-To-Live) auto-expiry 创建带 TTL(生存时间)自动过期的锁Creates a fair TTL lock 创建公平TTL锁
-
Method Details
-
lock
-
lock
Creates a local lock with specified configuration 使用指定配置创建本地锁- Parameters:
config- the lock configuration | 锁配置- Returns:
- the local lock | 本地锁
-
fairLock
-
readWriteLock
Creates a read-write lock allowing concurrent readers 创建允许并发读取的读写锁Examples | 示例:
ReadWriteLock<Long> rwLock = OpenLock.readWriteLock(); String data = rwLock.executeRead(() -> loadData()); rwLock.executeWrite(() -> saveData(newData));- Returns:
- the read-write lock | 读写锁
-
readWriteLock
Creates a read-write lock with specified configuration 使用指定配置创建读写锁- Parameters:
config- the lock configuration | 锁配置- Returns:
- the read-write lock | 读写锁
-
spinLock
-
spinLock
-
segmentLock
Creates a segment lock with default 16 segments 使用默认16个分段创建分段锁Segment locks reduce contention by mapping keys to separate lock segments.
分段锁通过将键映射到单独的锁段来减少争用。
- Type Parameters:
K- the key type | 键类型- Returns:
- the segment lock | 分段锁
-
segmentLock
Creates a segment lock with specified number of segments 使用指定分段数创建分段锁Examples | 示例:
SegmentLock<String> lock = OpenLock.segmentLock(32); lock.execute("user:123", () -> updateUser("123"));- Type Parameters:
K- the key type | 键类型- Parameters:
segments- the number of segments | 分段数- Returns:
- the segment lock | 分段锁
-
stampedLock
Creates a stamped lock adapter with optimistic read support 创建支持乐观读的戳记锁适配器Stamped locks offer higher throughput for read-heavy workloads via optimistic reads. Note: StampedLock is NOT reentrant and has limited virtual thread support.
戳记锁通过乐观读为读密集型工作负载提供更高吞吐量。 注意:StampedLock 不可重入,且虚拟线程支持有限。
Examples | 示例:
StampedLockAdapter stampedLock = OpenLock.stampedLock(); String data = stampedLock.optimisticRead(() -> readData()); stampedLock.executeWrite(() -> writeData());- Returns:
- the stamped lock adapter | 戳记锁适配器
-
stampedLock
Creates a stamped lock adapter with specified configuration 使用指定配置创建戳记锁适配器- Parameters:
config- the lock configuration | 锁配置- Returns:
- the stamped lock adapter | 戳记锁适配器
-
retryLock
Creates a retry lock wrapping a new local lock with default retry settings 使用默认重试设置包装新本地锁创建重试锁Retries lock acquisition with exponential backoff on failure.
锁获取失败时使用指数退避重试。
Examples | 示例:
Lock<Long> retryLock = OpenLock.retryLock(); retryLock.execute(() -> doWork());- Returns:
- the retry lock | 重试锁
-
retryLock
Creates a retry lock builder wrapping the specified lock 创建包装指定锁的重试锁构建器Examples | 示例:
Lock<Long> retryLock = OpenLock.retryLock(existingLock) .maxRetries(5) .retryDelay(Duration.ofMillis(200)) .backoffMultiplier(1.5) .build();- Type Parameters:
T- the lock token type | 锁令牌类型- Parameters:
delegate- the lock to wrap with retry logic | 要包装重试逻辑的锁- Returns:
- the retry lock builder | 重试锁构建器
-
ttlLock
Creates a lock with TTL (Time-To-Live) auto-expiry 创建带 TTL(生存时间)自动过期的锁If the lock is held beyond the TTL, it is marked as expired for monitoring. The actual lock release still depends on the holder calling unlock(). Use
TtlLock.isExpired()to detect and handle expired locks.如果锁持有超过TTL,将被标记为过期以供监控。 实际锁释放仍取决于持有者调用 unlock()。 使用
TtlLock.isExpired()检测和处理过期锁。Examples | 示例:
Lock<Long> ttlLock = OpenLock.ttlLock(Duration.ofSeconds(30)); ttlLock.execute(() -> processTask());- Parameters:
ttl- the maximum time a lock can be held | 锁可持有的最长时间- Returns:
- the TTL lock | TTL锁
-
ttlLock
-
observableLock
Creates an observable lock that fires events to listeners 创建向监听器触发事件的可观察锁Examples | 示例:
Lock<Long> observable = OpenLock.observableLock("myLock", event -> log.info("Lock event: {}", event)); observable.execute(() -> doWork());- Parameters:
lockName- the lock name for event identification | 用于事件标识的锁名称listeners- the event listeners | 事件监听器- Returns:
- the observable lock | 可观察锁
-
observableLock
public static <T> Lock<T> observableLock(Lock<T> delegate, String lockName, LockListener... listeners) Wraps an existing lock with event observation 用事件观察包装现有锁- Type Parameters:
T- the lock token type | 锁令牌类型- Parameters:
delegate- the lock to observe | 要观察的锁lockName- the lock name for event identification | 用于事件标识的锁名称listeners- the event listeners | 事件监听器- Returns:
- the observable lock | 可观察锁
-
namedLockFactory
Creates a named lock factory with default settings 使用默认设置创建命名锁工厂Examples | 示例:
NamedLockFactory factory = OpenLock.namedLockFactory(); factory.execute("order:12345", () -> processOrder("12345"));- Returns:
- the named lock factory | 命名锁工厂
-
namedLockFactory
Creates a named lock factory with specified stripe count 使用指定条纹数创建命名锁工厂- Parameters:
stripes- the number of stripes | 条纹数- Returns:
- the named lock factory | 命名锁工厂
-
lockGroup
Creates a lock group builder for atomic multi-lock acquisition 创建用于原子多锁获取的锁组构建器Lock groups prevent deadlocks by acquiring locks in consistent order.
锁组通过以一致的顺序获取锁来防止死锁。
Examples | 示例:
try (var guard = OpenLock.lockGroup() .add(lockA).add(lockB).add(lockC) .timeout(Duration.ofSeconds(10)) .build().lockAll()) { // All locks acquired atomically | 原子获取所有锁 transferFunds(accountA, accountB, accountC); }- Returns:
- the lock group builder | 锁组构建器
-
manager
Gets the default singleton lock manager 获取默认单例锁管理器- Returns:
- the default lock manager | 默认锁管理器
-
manager
Creates a new lock manager with specified configuration 使用指定配置创建新的锁管理器- Parameters:
config- the lock configuration | 锁配置- Returns:
- the lock manager | 锁管理器
-
execute
Executes action with a new temporary lock 使用新的临时锁执行操作- Parameters:
action- the action to execute | 要执行的操作
-
executeWithResult
Executes supplier with a new temporary lock and returns result 使用新的临时锁执行并返回结果- Type Parameters:
R- the result type | 结果类型- Parameters:
supplier- the supplier to execute | 要执行的供应者- Returns:
- the result | 结果
-
configBuilder
Creates a lock configuration builder 创建锁配置构建器- Returns:
- the configuration builder | 配置构建器
-
defaultConfig
Gets default lock configuration 获取默认锁配置- Returns:
- the default configuration | 默认配置
-
distributedConfigBuilder
Creates a distributed lock configuration builder 创建分布式锁配置构建器- Returns:
- the configuration builder | 配置构建器
-
defaultDistributedConfig
Gets default distributed lock configuration 获取默认分布式锁配置- Returns:
- the default configuration | 默认配置
-