Class SpinLock

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

public class SpinLock extends Object implements Lock<Long>
Spin Lock Implementation for Short Critical Sections 短临界区自旋锁实现

A spin lock implementation that busy-waits for the lock, suitable for very short critical sections where lock contention is expected to be brief.

一种忙等待锁的自旋锁实现,适用于锁争用预期较短的极短临界区。

Features | 主要功能:

  • Optimized for nanosecond-level operations - 针对纳秒级操作优化
  • Configurable spin count before yielding - 可配置让步前的自旋次数
  • Optional reentrant support - 可选的可重入支持
  • No OS-level context switching overhead - 无操作系统级上下文切换开销

Usage Examples | 使用示例:

// Create spin lock | 创建自旋锁
SpinLock lock = new SpinLock();

// Best for very short critical sections | 最适合极短临界区
lock.execute(() -> {
    counter.incrementAndGet();
});

// Custom spin count | 自定义自旋次数
SpinLock customLock = new SpinLock(
    LockConfig.builder().spinCount(2000).build());

Performance | 性能特性:

  • Best for operations measured in nanoseconds - 最适合纳秒级操作
  • Yields after max spin count to prevent CPU starvation - 达到最大自旋次数后让步以防止CPU饥饿
  • For longer operations, use LocalLock - 对于较长操作,请使用LocalLock

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 Details

    • SpinLock

      public SpinLock()
      Creates a spin lock with default configuration 使用默认配置创建自旋锁
    • SpinLock

      public SpinLock(LockConfig config)
      Creates a spin 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 number of holds on this lock by the current thread 获取当前线程对此锁的持有次数
      Returns:
      the hold count | 持有计数