Class LocalLock

java.lang.Object
cloud.opencode.base.lock.local.LocalLock
All Implemented Interfaces:
Lock<Long>, AutoCloseable

public class LocalLock extends Object implements Lock<Long>
Local Lock Implementation Based on JDK ReentrantLock 基于JDK ReentrantLock的本地锁实现

A high-performance local lock implementation with Virtual Thread support, avoiding synchronized keyword to prevent thread pinning.

高性能本地锁实现,支持虚拟线程,避免使用synchronized关键字以防止线程固定。

Features | 主要功能:

  • Virtual Thread friendly (no pinning) - 虚拟线程友好(无固定)
  • Reentrant lock support - 支持可重入锁
  • Fair/unfair lock modes - 公平/非公平锁模式
  • Configurable timeout - 可配置超时
  • Built-in metrics collection - 内置指标收集
  • Try-with-resources support - 支持try-with-resources

Usage Examples | 使用示例:

// Create lock with default configuration | 使用默认配置创建锁
LocalLock lock = new LocalLock();

// Execute with automatic release | 自动释放的执行
lock.execute(() -> {
    // Critical section | 临界区
});

// Try-with-resources pattern | try-with-resources模式
try (var guard = lock.lock()) {
    // Critical section | 临界区
}

// With custom configuration | 使用自定义配置
LocalLock fairLock = new LocalLock(LockConfig.builder()
    .fair(true)
    .enableMetrics(true)
    .build());

Performance | 性能特性:

  • Low contention overhead - 低争用开销
  • Metrics tracking with minimal impact - 最小影响的指标跟踪

Security | 安全性:

  • Thread-safe: Yes - 线程安全: 是
  • Virtual Thread friendly: Yes - 虚拟线程友好: 是
  • Reentrant: Configurable - 可重入: 可配置
Since:
JDK 25, opencode-base-lock V1.0.0
Author:
Leon Soo www.LeonSoo.com
See Also:
  • Constructor Summary

    Constructors
    Constructor
    Description
    Creates a local lock with default configuration 使用默认配置创建本地锁
    Creates a local lock with specified configuration 使用指定配置创建本地锁
  • Method Summary

    Modifier and Type
    Method
    Description
    int
    Gets the hold count for current thread 获取当前线程的持有计数
    Gets the lock metrics if metrics collection is enabled 如果启用了指标收集,则获取锁指标
    int
    Gets the estimated number of threads waiting to acquire this lock 获取等待获取此锁的线程估计数量
    Gets the current lock token 获取当前锁令牌
    boolean
    Checks if any threads are waiting to acquire this lock 检查是否有线程正在等待获取此锁
    boolean
    Checks if this lock uses fair ordering policy 检查此锁是否使用公平排序策略
    boolean
    Checks if lock is held by current thread 检查当前线程是否持有锁
    Acquires the lock, blocking until available 获取锁,阻塞直到可用
    lock(Duration timeout)
    Acquires the lock with timeout 带超时获取锁
    Acquires the lock interruptibly 可中断地获取锁
    boolean
    Tries to acquire the lock immediately without waiting 立即尝试获取锁,不等待
    boolean
    tryLock(Duration timeout)
    Tries to acquire the lock with timeout 带超时尝试获取锁
    void
    Releases the lock 释放锁

    Methods inherited from class Object

    clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

    Methods inherited from interface Lock

    close, execute, execute, executeWithResult, executeWithResult
  • Constructor Details

    • LocalLock

      public LocalLock()
      Creates a local lock with default configuration 使用默认配置创建本地锁
    • LocalLock

      public LocalLock(LockConfig config)
      Creates a local lock with specified configuration 使用指定配置创建本地锁
      Parameters:
      config - the lock configuration | 锁配置
  • Method Details

    • lock

      public LockGuard<Long> lock()
      Description copied from interface: Lock
      Acquires the lock, blocking until available 获取锁,阻塞直到可用

      Examples | 示例:

      try (var guard = lock.lock()) {
          // Use the lock | 使用锁
      } // Automatically released | 自动释放
      
      Specified by:
      lock in interface Lock<Long>
      Returns:
      lock guard for auto-release | 用于自动释放的锁守卫
    • lock

      public LockGuard<Long> lock(Duration timeout)
      Description copied from interface: Lock
      Acquires the lock with timeout 带超时获取锁

      Examples | 示例:

      try (var guard = lock.lock(Duration.ofSeconds(5))) {
          // Use the lock | 使用锁
      }
      
      Specified by:
      lock in interface Lock<Long>
      Parameters:
      timeout - maximum time to wait | 最大等待时间
      Returns:
      lock guard for auto-release | 用于自动释放的锁守卫
    • tryLock

      public boolean tryLock()
      Description copied from interface: Lock
      Tries to acquire the lock immediately without waiting 立即尝试获取锁,不等待

      Examples | 示例:

      if (lock.tryLock()) {
          try {
              // Use the lock | 使用锁
          } finally {
              lock.unlock();
          }
      }
      
      Specified by:
      tryLock in interface Lock<Long>
      Returns:
      true if lock acquired, false otherwise | 获取成功返回true,否则返回false
    • tryLock

      public boolean tryLock(Duration timeout)
      Description copied from interface: Lock
      Tries to acquire the lock with timeout 带超时尝试获取锁
      Specified by:
      tryLock in interface Lock<Long>
      Parameters:
      timeout - maximum time to wait | 最大等待时间
      Returns:
      true if lock acquired, false otherwise | 获取成功返回true,否则返回false
    • lockInterruptibly

      public LockGuard<Long> lockInterruptibly() throws InterruptedException
      Description copied from interface: Lock
      Acquires the lock interruptibly 可中断地获取锁
      Specified by:
      lockInterruptibly in interface Lock<Long>
      Returns:
      lock guard for auto-release | 用于自动释放的锁守卫
      Throws:
      InterruptedException - if interrupted while waiting | 等待时被中断则抛出
    • unlock

      public void unlock()
      Description copied from interface: Lock
      Releases the lock 释放锁

      Should be called in a finally block if not using try-with-resources.

      如果不使用 try-with-resources,应在 finally 块中调用。

      Specified by:
      unlock in interface Lock<Long>
    • isHeldByCurrentThread

      public boolean isHeldByCurrentThread()
      Description copied from interface: Lock
      Checks if lock is held by current thread 检查当前线程是否持有锁
      Specified by:
      isHeldByCurrentThread in interface Lock<Long>
      Returns:
      true if current thread holds the lock | 当前线程持有锁返回true
    • getToken

      public Optional<Long> getToken()
      Description copied from interface: Lock
      Gets the current lock token 获取当前锁令牌
      Specified by:
      getToken in interface Lock<Long>
      Returns:
      lock token, or empty if not locked | 锁令牌,未锁定时返回空
    • getHoldCount

      public int getHoldCount()
      Gets the hold count for current thread 获取当前线程的持有计数
      Returns:
      the number of holds on this lock | 此锁的持有次数
    • isFair

      public boolean isFair()
      Checks if this lock uses fair ordering policy 检查此锁是否使用公平排序策略
      Returns:
      true if fair | true表示公平锁
    • hasQueuedThreads

      public boolean hasQueuedThreads()
      Checks if any threads are waiting to acquire this lock 检查是否有线程正在等待获取此锁
      Returns:
      true if there are waiting threads | true表示有等待线程
    • getQueueLength

      public int getQueueLength()
      Gets the estimated number of threads waiting to acquire this lock 获取等待获取此锁的线程估计数量
      Returns:
      the number of waiting threads | 等待线程数
    • getMetrics

      public Optional<LockMetrics> getMetrics()
      Gets the lock metrics if metrics collection is enabled 如果启用了指标收集,则获取锁指标
      Returns:
      lock metrics, or empty if metrics disabled | 锁指标,如果禁用则为空