Class FencingTokenGenerator

java.lang.Object
cloud.opencode.base.lock.token.FencingTokenGenerator

public final class FencingTokenGenerator extends Object
Fencing Token Generator with Optional ID Module Delegation 支持可选 ID 模块委托的 Fencing Token 生成器

Generates unique fencing tokens for distributed lock scenarios. If the ID module (opencode-base-id) is available, it delegates to OpenId for higher quality tokens (TSID/ULID). Otherwise, falls back to local generation.

为分布式锁场景生成唯一的防护令牌。 如果 ID 模块可用,则委托给 OpenId 生成更高质量的令牌(TSID/ULID)。 否则降级到本地生成。

Token Types | 令牌类型:

  • With ID module: TSID (time-sorted, 64-bit) or ULID (128-bit) - 使用TSID或ULID
  • Without ID module: UUID-based or AtomicLong - 使用UUID或AtomicLong

Usage Examples | 使用示例:

// Generate string token (recommended for distributed locks)
String token = FencingTokenGenerator.generateStringToken();

// Generate long token (for local locks)
long token = FencingTokenGenerator.generateLongToken();

// Check if ID module is available
boolean hasIdModule = FencingTokenGenerator.isIdModuleAvailable();

Security | 安全性:

  • Thread-safe: Yes - 线程安全: 是
  • Monotonic: Yes (with ID module) - 单调递增: 是(使用ID模块时)

Features | 主要功能:

  • Generates monotonically increasing fencing tokens - 生成单调递增的防护令牌
  • Prevents stale lock holders from corrupting data - 防止过期锁持有者损坏数据
Since:
JDK 25, opencode-base-lock V1.0.0
Author:
Leon Soo www.LeonSoo.com
See Also:
  • Method Details

    • isIdModuleAvailable

      public static boolean isIdModuleAvailable()
      Checks if the ID module is available. 检查 ID 模块是否可用
      Returns:
      true if ID module is available - 如果 ID 模块可用返回 true
    • generateStringToken

      public static String generateStringToken()
      Generates a unique string token for fencing. 生成用于防护的唯一字符串令牌

      If ID module is available, uses TSID (time-sorted, compact). Otherwise, uses UUID-based fallback.

      Returns:
      unique string token - 唯一字符串令牌
    • generateLongToken

      public static long generateLongToken()
      Generates a unique long token for fencing. 生成用于防护的唯一长整型令牌

      If ID module is available, uses TSID (time-sorted, 64-bit). Otherwise, uses AtomicLong-based fallback.

      Returns:
      unique long token - 唯一长整型令牌
    • generatePrefixedToken

      public static String generatePrefixedToken(String prefix)
      Generates a token with specified prefix. 生成带指定前缀的令牌
      Parameters:
      prefix - the prefix to add - 要添加的前缀
      Returns:
      prefixed token - 带前缀的令牌