Interface Lock<T>

Type Parameters:
T - the type of lock token | 锁令牌类型
All Superinterfaces:
AutoCloseable
All Known Subinterfaces:
DistributedLock
All Known Implementing Classes:
LocalLock, ObservableLock, RetryLock, SpinLock, TtlLock

public interface Lock<T> extends AutoCloseable
Unified Lock Interface for Local and Distributed Locks 本地锁和分布式锁的统一抽象接口

Provides a unified abstraction for both local and distributed locks, supporting try-with-resources pattern for automatic release.

提供本地锁和分布式锁的统一抽象,支持 try-with-resources 模式自动释放。

Features | 主要功能:

  • Automatic release with try-with-resources - 通过 try-with-resources 自动释放
  • Timeout support for lock acquisition - 支持超时获取锁
  • Interruptible lock acquisition - 支持可中断的锁获取
  • Token-based lock identification - 基于令牌的锁标识
  • Convenient execute methods - 便捷的执行方法

Usage Examples | 使用示例:

// 1. Basic usage with try-with-resources | 基本用法
try (var guard = lock.lock()) {
    // Critical section | 临界区
}

// 2. Try lock with timeout | 带超时尝试获取锁
if (lock.tryLock(Duration.ofSeconds(5))) {
    try {
        // Critical section | 临界区
    } finally {
        lock.unlock();
    }
}

// 3. Execute with lock (recommended) | 使用锁执行(推荐)
lock.execute(() -> {
    // Critical section | 临界区
});

// 4. Execute with result | 执行并返回结果
String result = lock.executeWithResult(() -> {
    return computeValue();
});

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 Type
    Method
    Description
    default void
    Releases lock if held by current thread 如果当前线程持有锁则释放
    default void
    execute(Runnable action)
    Executes action with lock held 持有锁执行操作
    default void
    execute(Runnable action, Duration timeout)
    Executes action with lock and timeout 带超时持有锁执行操作
    default <R> R
    Executes supplier with lock and returns result 持有锁执行并返回结果
    default <R> R
    executeWithResult(Supplier<R> supplier, Duration timeout)
    Executes supplier with lock, timeout and returns result 带超时持有锁执行并返回结果
    Gets the current lock token 获取当前锁令牌
    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 释放锁
  • Method Details

    • lock

      LockGuard<T> lock()
      Acquires the lock, blocking until available 获取锁,阻塞直到可用

      Examples | 示例:

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

      LockGuard<T> lock(Duration timeout)
      Acquires the lock with timeout 带超时获取锁

      Examples | 示例:

      try (var guard = lock.lock(Duration.ofSeconds(5))) {
          // Use the lock | 使用锁
      }
      
      Parameters:
      timeout - maximum time to wait | 最大等待时间
      Returns:
      lock guard for auto-release | 用于自动释放的锁守卫
      Throws:
      OpenLockTimeoutException - if timeout exceeded | 超时时抛出
    • tryLock

      boolean tryLock()
      Tries to acquire the lock immediately without waiting 立即尝试获取锁,不等待

      Examples | 示例:

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

      boolean tryLock(Duration timeout)
      Tries to acquire the lock with timeout 带超时尝试获取锁
      Parameters:
      timeout - maximum time to wait | 最大等待时间
      Returns:
      true if lock acquired, false otherwise | 获取成功返回true,否则返回false
    • lockInterruptibly

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

      void unlock()
      Releases the lock 释放锁

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

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

    • isHeldByCurrentThread

      boolean isHeldByCurrentThread()
      Checks if lock is held by current thread 检查当前线程是否持有锁
      Returns:
      true if current thread holds the lock | 当前线程持有锁返回true
    • getToken

      Optional<T> getToken()
      Gets the current lock token 获取当前锁令牌
      Returns:
      lock token, or empty if not locked | 锁令牌,未锁定时返回空
    • execute

      default void execute(Runnable action)
      Executes action with lock held 持有锁执行操作

      Examples | 示例:

      lock.execute(() -> {
          // This code runs with lock held | 此代码在持有锁时运行
          updateSharedState();
      });
      
      Parameters:
      action - the action to execute | 要执行的操作
    • execute

      default void execute(Runnable action, Duration timeout)
      Executes action with lock and timeout 带超时持有锁执行操作
      Parameters:
      action - the action to execute | 要执行的操作
      timeout - maximum time to wait for lock | 获取锁的最大等待时间
    • executeWithResult

      default <R> R executeWithResult(Supplier<R> supplier)
      Executes supplier with lock and returns result 持有锁执行并返回结果

      Examples | 示例:

      String result = lock.executeWithResult(() -> {
          return readSharedState();
      });
      
      Type Parameters:
      R - the result type | 结果类型
      Parameters:
      supplier - the supplier to execute | 要执行的供应者
      Returns:
      the result | 结果
    • executeWithResult

      default <R> R executeWithResult(Supplier<R> supplier, Duration timeout)
      Executes supplier with lock, timeout and returns result 带超时持有锁执行并返回结果
      Type Parameters:
      R - the result type | 结果类型
      Parameters:
      supplier - the supplier to execute | 要执行的供应者
      timeout - maximum time to wait for lock | 获取锁的最大等待时间
      Returns:
      the result | 结果
    • close

      default void close()
      Releases lock if held by current thread 如果当前线程持有锁则释放
      Specified by:
      close in interface AutoCloseable