Class StampedLockAdapter

java.lang.Object
cloud.opencode.base.lock.local.StampedLockAdapter
All Implemented Interfaces:
ReadWriteLock<Long>

public class StampedLockAdapter extends Object implements ReadWriteLock<Long>
StampedLock Adapter - Safe Wrapper Around JDK StampedLock StampedLock 适配器 - JDK StampedLock 的安全封装

Provides a safe, high-level API around StampedLock implementing ReadWriteLock<Long>. The stamp returned by the underlying StampedLock is used directly as the lock token.

围绕 StampedLock 提供安全的高级 API,实现 ReadWriteLock<Long>。底层 StampedLock 返回的戳记直接用作锁令牌。

WARNING: StampedLock is NOT reentrant | 警告:StampedLock 不可重入

Unlike LocalReadWriteLock, StampedLock does not support reentrant locking. A thread that already holds a write lock and attempts to acquire it again will deadlock. Similarly, a thread holding a read lock cannot upgrade to a write lock via this adapter.

LocalReadWriteLock 不同,StampedLock 不支持可重入锁定。 已持有写锁的线程再次尝试获取将导致死锁。 同样,持有读锁的线程无法通过此适配器升级为写锁。

WARNING: Limited Virtual Thread support | 警告:有限的虚拟线程支持

StampedLock uses spin-based optimizations that are not ideal for virtual threads. For virtual-thread-heavy workloads, prefer LocalReadWriteLock.

StampedLock 使用基于自旋的优化,对虚拟线程不太理想。 对于虚拟线程密集的工作负载,建议使用 LocalReadWriteLock

Features | 主要功能:

  • Optimistic read support for high-throughput reads - 乐观读支持高吞吐量读取
  • Automatic fallback from optimistic to pessimistic read - 从乐观读自动降级到悲观读
  • Multiple concurrent readers with exclusive writer - 多个并发读取者与独占写入者
  • Stamp-based token management - 基于戳记的令牌管理
  • try-with-resources support via LockGuard - 通过 LockGuard 支持 try-with-resources

Usage Examples | 使用示例:

// Create adapter | 创建适配器
StampedLockAdapter adapter = new StampedLockAdapter();

// Optimistic read (best performance) | 乐观读(最佳性能)
String value = adapter.optimisticRead(() -> sharedData);

// Read with lock | 加锁读取
try (var guard = adapter.readLock().lock()) {
    // Read operations | 读操作
}

// Write with lock | 加锁写入
try (var guard = adapter.writeLock().lock()) {
    // Write operations | 写操作
}

// Using execute methods | 使用执行方法
adapter.executeRead(() -> readData());
adapter.executeWrite(() -> writeData());

Performance | 性能特性:

  • Optimistic reads avoid locking entirely when no writes occur - 无写入时乐观读完全避免加锁
  • Higher throughput than ReentrantReadWriteLock under low contention - 低竞争下比 ReentrantReadWriteLock 更高吞吐量
  • Not suitable for long-held locks or reentrant patterns - 不适合长期持有锁或可重入模式

Security | 安全性:

  • Thread-safe: Yes - 线程安全: 是
  • Virtual Thread friendly: Limited (spin-based) - 虚拟线程友好: 有限(基于自旋)
  • Reentrant: No - 可重入: 否
Since:
JDK 25, opencode-base-lock V1.0.3
Author:
Leon Soo www.LeonSoo.com
See Also:
  • Constructor Details

    • StampedLockAdapter

      public StampedLockAdapter()
      Creates a StampedLock adapter with default configuration 使用默认配置创建 StampedLock 适配器
    • StampedLockAdapter

      public StampedLockAdapter(LockConfig config)
      Creates a StampedLock adapter with specified configuration 使用指定配置创建 StampedLock 适配器

      Only the defaultTimeout from the configuration is used. The fair and reentrant settings are ignored because StampedLock is always unfair and non-reentrant.

      仅使用配置中的 defaultTimeoutfairreentrant 设置被忽略,因为 StampedLock 始终是非公平且不可重入的。

      Parameters:
      config - the lock configuration | 锁配置
      Throws:
      NullPointerException - if config is null | 如果 config 为 null 则抛出
  • Method Details

    • readLock

      public Lock<Long> readLock()
      Description copied from interface: ReadWriteLock
      Gets the read lock for concurrent read access 获取用于并发读取访问的读锁
      Specified by:
      readLock in interface ReadWriteLock<Long>
      Returns:
      the read lock | 读锁
    • writeLock

      public Lock<Long> writeLock()
      Description copied from interface: ReadWriteLock
      Gets the write lock for exclusive write access 获取用于独占写入访问的写锁
      Specified by:
      writeLock in interface ReadWriteLock<Long>
      Returns:
      the write lock | 写锁
    • optimisticRead

      public <R> R optimisticRead(Supplier<R> reader)
      Performs an optimistic read operation with automatic fallback 执行乐观读操作并自动降级

      First attempts an optimistic read (no lock acquisition). If the data is concurrently modified during the read, automatically falls back to a pessimistic read lock using the configured default timeout.

      首先尝试乐观读(无需获取锁)。如果在读取期间数据被并发修改, 则自动降级为使用配置的默认超时的悲观读锁。

      Examples | 示例:

      StampedLockAdapter adapter = new StampedLockAdapter();
      String value = adapter.optimisticRead(() -> sharedMap.get("key"));
      
      Type Parameters:
      R - the result type | 结果类型
      Parameters:
      reader - the read operation to execute | 要执行的读操作
      Returns:
      the result of the read operation | 读操作的结果
      Throws:
      NullPointerException - if reader is null | 如果 reader 为 null 则抛出
      OpenLockTimeoutException - if fallback lock acquisition times out | 降级锁获取超时时抛出
      OpenLockAcquireException - if fallback lock acquisition is interrupted | 降级锁获取被中断时抛出
    • optimisticRead

      public <R> R optimisticRead(Supplier<R> reader, Duration timeout)
      Performs an optimistic read with timeout for fallback lock acquisition 执行乐观读操作,降级时使用指定超时

      First attempts an optimistic read (no lock acquisition). If the data is concurrently modified during the read, falls back to a pessimistic read lock with the specified timeout.

      首先尝试乐观读(无需获取锁)。如果在读取期间数据被并发修改, 则降级为具有指定超时的悲观读锁。

      Type Parameters:
      R - the result type | 结果类型
      Parameters:
      reader - the read operation to execute | 要执行的读操作
      timeout - timeout for fallback pessimistic read lock | 降级悲观读锁的超时时间
      Returns:
      the result of the read operation | 读操作的结果
      Throws:
      NullPointerException - if reader or timeout is null | 如果 reader 或 timeout 为 null 则抛出
      OpenLockTimeoutException - if fallback lock acquisition times out | 降级锁获取超时时抛出
      OpenLockAcquireException - if fallback lock acquisition is interrupted | 降级锁获取被中断时抛出
    • isReadLocked

      public boolean isReadLocked()
      Checks if the lock is currently held for reading 检查锁当前是否被读取持有
      Returns:
      true if any thread holds a read lock | 如果任何线程持有读锁则返回 true
    • isWriteLocked

      public boolean isWriteLocked()
      Checks if the lock is currently held for writing 检查锁当前是否被写入持有
      Returns:
      true if any thread holds the write lock | 如果任何线程持有写锁则返回 true