Class ObservableLock<T>

java.lang.Object
cloud.opencode.base.lock.event.ObservableLock<T>
Type Parameters:
T - the type of lock token | 锁令牌类型
All Implemented Interfaces:
Lock<T>, AutoCloseable

public class ObservableLock<T> extends Object implements Lock<T>
Observable Lock Decorator with Event Notification 带事件通知的可观察锁装饰器

A decorator that wraps any Lock implementation and fires LockEvent notifications to registered LockListeners on lock lifecycle transitions.

一个装饰器,包装任意 Lock 实现,并在锁生命周期转换时 向注册的 LockListener 发送 LockEvent 通知。

Features | 主要功能:

  • Transparent decorator pattern - 透明装饰器模式
  • Thread-safe listener management - 线程安全的监听器管理
  • Listener exception isolation - 监听器异常隔离
  • Wait-time tracking for acquisition events - 获取事件的等待时间跟踪
  • Fluent API for listener registration - 流式API用于监听器注册

Usage Examples | 使用示例:

// Wrap an existing lock | 包装现有锁
Lock<Long> baseLock = new LocalLock();
ObservableLock<Long> lock = new ObservableLock<>(baseLock, "order-lock");

// Add listeners | 添加监听器
lock.addListener(event -> log.info("{}: {}", event.type(), event.lockName()));
lock.addListener(event -> metrics.record(event));

// Use like a normal lock | 像普通锁一样使用
try (var guard = lock.lock()) {
    // Critical section | 临界区
}
// ACQUIRED and RELEASED events are fired automatically
// ACQUIRED和RELEASED事件自动触发

// With initial listeners | 带初始监听器
ObservableLock<Long> lock2 = new ObservableLock<>(baseLock, "stock-lock",
    auditListener, metricsListener);

Security | 安全性:

  • Thread-safe: Yes (CopyOnWriteArrayList for listeners) - 线程安全: 是(监听器使用CopyOnWriteArrayList)
  • Exception isolation: Listener exceptions are caught and suppressed - 异常隔离: 监听器异常被捕获并抑制
  • Virtual Thread friendly: Yes - 虚拟线程友好: 是
Since:
JDK 25, opencode-base-lock V1.0.3
Author:
Leon Soo www.LeonSoo.com
See Also:
  • Constructor Details

    • ObservableLock

      public ObservableLock(Lock<T> delegate, String lockName)
      Creates an observable lock wrapping the given delegate 创建包装给定委托的可观察锁
      Parameters:
      delegate - the underlying lock to decorate | 要装饰的底层锁
      lockName - the name for this lock (used in events) | 此锁的名称(用于事件)
      Throws:
      NullPointerException - if delegate or lockName is null | 如果delegate或lockName为null则抛出
    • ObservableLock

      public ObservableLock(Lock<T> delegate, String lockName, LockListener... listeners)
      Creates an observable lock with initial listeners 创建带初始监听器的可观察锁
      Parameters:
      delegate - the underlying lock to decorate | 要装饰的底层锁
      lockName - the name for this lock (used in events) | 此锁的名称(用于事件)
      listeners - the initial listeners to register | 要注册的初始监听器
      Throws:
      NullPointerException - if delegate or lockName is null | 如果delegate或lockName为null则抛出
  • Method Details

    • addListener

      public ObservableLock<T> addListener(LockListener listener)
      Adds a listener to receive lock events 添加监听器以接收锁事件
      Parameters:
      listener - the listener to add | 要添加的监听器
      Returns:
      this observable lock for fluent chaining | 此可观察锁用于链式调用
      Throws:
      NullPointerException - if listener is null | 如果listener为null则抛出
    • removeListener

      public ObservableLock<T> removeListener(LockListener listener)
      Removes a listener from receiving lock events 移除监听器使其不再接收锁事件
      Parameters:
      listener - the listener to remove | 要移除的监听器
      Returns:
      this observable lock for fluent chaining | 此可观察锁用于链式调用
    • getLockName

      public String getLockName()
      Gets the lock name used in events 获取事件中使用的锁名称
      Returns:
      the lock name | 锁名称
    • lock

      public LockGuard<T> 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<T>
      Returns:
      lock guard for auto-release | 用于自动释放的锁守卫
    • lock

      public LockGuard<T> 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<T>
      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<T>
      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<T>
      Parameters:
      timeout - maximum time to wait | 最大等待时间
      Returns:
      true if lock acquired, false otherwise | 获取成功返回true,否则返回false
    • lockInterruptibly

      public LockGuard<T> lockInterruptibly() throws InterruptedException
      Description copied from interface: Lock
      Acquires the lock interruptibly 可中断地获取锁
      Specified by:
      lockInterruptibly in interface Lock<T>
      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<T>
    • isHeldByCurrentThread

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

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