Class OpenLock

java.lang.Object
cloud.opencode.base.lock.OpenLock

public final class OpenLock extends Object
OpenLock Facade - Unified Entry Point for Lock Component 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 Details

    • lock

      public static Lock<Long> lock()
      Creates a local reentrant lock with default configuration 使用默认配置创建本地可重入锁

      Examples | 示例:

      Lock<Long> lock = OpenLock.lock();
      lock.execute(() -> doWork());
      
      Returns:
      the local lock | 本地锁
    • lock

      public static Lock<Long> lock(LockConfig config)
      Creates a local lock with specified configuration 使用指定配置创建本地锁
      Parameters:
      config - the lock configuration | 锁配置
      Returns:
      the local lock | 本地锁
    • fairLock

      public static Lock<Long> fairLock()
      Creates a fair lock that grants access in FIFO order 创建按FIFO顺序授予访问权限的公平锁

      Fair locks may have lower throughput but prevent starvation.

      公平锁可能具有较低的吞吐量,但可以防止饥饿。

      Returns:
      the fair lock | 公平锁
    • readWriteLock

      public static ReadWriteLock<Long> 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

      public static ReadWriteLock<Long> readWriteLock(LockConfig config)
      Creates a read-write lock with specified configuration 使用指定配置创建读写锁
      Parameters:
      config - the lock configuration | 锁配置
      Returns:
      the read-write lock | 读写锁
    • spinLock

      public static Lock<Long> spinLock()
      Creates a spin lock for very short critical sections 为极短临界区创建自旋锁

      Performance | 性能特性:

      Best for critical sections measured in nanoseconds. For longer operations, use regular locks.

      最适合以纳秒为单位的临界区。对于较长操作,请使用常规锁。

      Returns:
      the spin lock | 自旋锁
    • spinLock

      public static Lock<Long> spinLock(int maxSpinCount)
      Creates a spin lock with custom max spin count 使用自定义最大自旋次数创建自旋锁
      Parameters:
      maxSpinCount - the maximum spin count before yielding | 让步前的最大自旋次数
      Returns:
      the spin lock | 自旋锁
    • segmentLock

      public static <K> SegmentLock<K> 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

      public static <K> SegmentLock<K> segmentLock(int segments)
      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

      public static StampedLockAdapter 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

      public static StampedLockAdapter stampedLock(LockConfig config)
      Creates a stamped lock adapter with specified configuration 使用指定配置创建戳记锁适配器
      Parameters:
      config - the lock configuration | 锁配置
      Returns:
      the stamped lock adapter | 戳记锁适配器
    • retryLock

      public static Lock<Long> 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

      public static <T> RetryLock.Builder<T> retryLock(Lock<T> delegate)
      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

      public static Lock<Long> ttlLock(Duration ttl)
      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

      public static Lock<Long> ttlLock(Duration ttl, boolean fair)
      Creates a fair TTL lock 创建公平TTL锁
      Parameters:
      ttl - the maximum time a lock can be held | 锁可持有的最长时间
      fair - whether the lock should be fair | 锁是否应该是公平的
      Returns:
      the TTL lock | TTL锁
    • observableLock

      public static Lock<Long> observableLock(String lockName, LockListener... listeners)
      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

      public static NamedLockFactory 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

      public static NamedLockFactory namedLockFactory(int stripes)
      Creates a named lock factory with specified stripe count 使用指定条纹数创建命名锁工厂
      Parameters:
      stripes - the number of stripes | 条纹数
      Returns:
      the named lock factory | 命名锁工厂
    • lockGroup

      public static LockGroup.Builder 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

      public static LockManager manager()
      Gets the default singleton lock manager 获取默认单例锁管理器
      Returns:
      the default lock manager | 默认锁管理器
    • manager

      public static LockManager manager(LockConfig config)
      Creates a new lock manager with specified configuration 使用指定配置创建新的锁管理器
      Parameters:
      config - the lock configuration | 锁配置
      Returns:
      the lock manager | 锁管理器
    • execute

      public static void execute(Runnable action)
      Executes action with a new temporary lock 使用新的临时锁执行操作
      Parameters:
      action - the action to execute | 要执行的操作
    • executeWithResult

      public static <R> R executeWithResult(Supplier<R> supplier)
      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

      public static LockConfig.Builder configBuilder()
      Creates a lock configuration builder 创建锁配置构建器
      Returns:
      the configuration builder | 配置构建器
    • defaultConfig

      public static LockConfig defaultConfig()
      Gets default lock configuration 获取默认锁配置
      Returns:
      the default configuration | 默认配置
    • distributedConfigBuilder

      public static DistributedLockConfig.Builder distributedConfigBuilder()
      Creates a distributed lock configuration builder 创建分布式锁配置构建器
      Returns:
      the configuration builder | 配置构建器
    • defaultDistributedConfig

      public static DistributedLockConfig defaultDistributedConfig()
      Gets default distributed lock configuration 获取默认分布式锁配置
      Returns:
      the default configuration | 默认配置