Class RetryLock<T>

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

public class RetryLock<T> extends Object implements Lock<T>
Retry Lock Decorator with Exponential Backoff 带指数退避的重试锁装饰器

A decorator that adds configurable retry logic with exponential backoff to any Lock implementation. When lock acquisition fails with a timeout, RetryLock automatically retries up to the configured number of attempts, applying exponential backoff between retries.

一个装饰器,为任何 Lock 实现添加可配置的指数退避重试逻辑。 当锁获取因超时失败时,RetryLock 会自动重试到配置的尝试次数, 并在重试之间应用指数退避。

Features | 主要功能:

  • Configurable max retries - 可配置最大重试次数
  • Exponential backoff with configurable multiplier - 可配置倍数的指数退避
  • Maximum delay cap to prevent unbounded waits - 最大延迟上限防止无限等待
  • Virtual Thread friendly (uses Thread.sleep) - 虚拟线程友好(使用 Thread.sleep)
  • Builder pattern for flexible configuration - 构建器模式灵活配置

Usage Examples | 使用示例:

// Wrap any lock with retry logic | 为任何锁添加重试逻辑
Lock<Long> base = new LocalLock();
RetryLock<Long> retryLock = RetryLock.builder(base)
    .maxRetries(5)
    .retryDelay(Duration.ofMillis(200))
    .backoffMultiplier(1.5)
    .maxDelay(Duration.ofSeconds(3))
    .build();

// Use like any other lock | 像其他锁一样使用
try (var guard = retryLock.lock()) {
    // Critical section | 临界区
}

// With defaults (3 retries, 100ms delay, 2x backoff, 5s max) | 使用默认值
RetryLock<Long> defaultRetry = new RetryLock<>(base);

Performance | 性能特性:

  • Minimal overhead on first attempt success - 首次成功时开销极小
  • Backoff prevents thundering herd on contention - 退避防止争用时的惊群效应

Security | 安全性:

  • Thread-safe: Yes (delegates to thread-safe lock) - 线程安全: 是(委托给线程安全锁)
  • Virtual Thread friendly: Yes - 虚拟线程友好: 是
  • Interrupt-aware: Yes - 中断感知: 是
Since:
JDK 25, opencode-base-lock V1.0.3
Author:
Leon Soo www.LeonSoo.com
See Also:
  • Constructor Details

    • RetryLock

      public RetryLock(Lock<T> delegate)
      Creates a retry lock with default configuration 使用默认配置创建重试锁

      Defaults: 3 retries, 100ms initial delay, 2x backoff, 5s max delay.

      默认值: 3次重试, 100ms初始延迟, 2倍退避, 5秒最大延迟。

      Parameters:
      delegate - the underlying lock to decorate | 要装饰的底层锁
      Throws:
      NullPointerException - if delegate is null | 如果delegate为null则抛出
    • RetryLock

      public RetryLock(Lock<T> delegate, int maxRetries, Duration retryDelay, double backoffMultiplier, Duration maxDelay)
      Creates a retry lock with custom configuration 使用自定义配置创建重试锁
      Parameters:
      delegate - the underlying lock to decorate | 要装饰的底层锁
      maxRetries - maximum retry attempts (must be >= 0) | 最大重试次数(必须 >= 0)
      retryDelay - initial delay between retries | 重试之间的初始延迟
      backoffMultiplier - backoff multiplier (must be >= 1.0) | 退避倍数(必须 >= 1.0)
      maxDelay - maximum delay cap | 最大延迟上限
      Throws:
      NullPointerException - if any argument is null | 如果任何参数为null则抛出
      IllegalArgumentException - if maxRetries invalid input: '<' 0 or backoffMultiplier invalid input: '<' 1.0 | 参数非法时抛出
  • Method Details

    • builder

      public static <T> RetryLock.Builder<T> builder(Lock<T> delegate)
      Creates a builder for configuring a retry lock 创建用于配置重试锁的构建器
      Type Parameters:
      T - the type of lock token | 锁令牌类型
      Parameters:
      delegate - the underlying lock to decorate | 要装饰的底层锁
      Returns:
      a new builder instance | 新的构建器实例
    • 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 | 锁令牌,未锁定时返回空
    • getMaxRetries

      public int getMaxRetries()
      Gets the maximum number of retry attempts 获取最大重试次数
      Returns:
      the max retries | 最大重试次数
    • getRetryDelay

      public Duration getRetryDelay()
      Gets the initial retry delay 获取初始重试延迟
      Returns:
      the retry delay | 重试延迟
    • getBackoffMultiplier

      public double getBackoffMultiplier()
      Gets the backoff multiplier 获取退避倍数
      Returns:
      the backoff multiplier | 退避倍数
    • getMaxDelay

      public Duration getMaxDelay()
      Gets the maximum delay cap 获取最大延迟上限
      Returns:
      the max delay | 最大延迟
    • getDelegate

      public Lock<T> getDelegate()
      Gets the underlying delegate lock 获取底层委托锁
      Returns:
      the delegate lock | 委托锁