Class SegmentIdGenerator

java.lang.Object
cloud.opencode.base.id.segment.SegmentIdGenerator
All Implemented Interfaces:
IdGenerator<Long>, AutoCloseable

public final class SegmentIdGenerator extends Object implements IdGenerator<Long>, AutoCloseable
Segment Mode ID Generator 号段模式ID生成器

Generates IDs using segment mode with double buffering for high performance. Segments are fetched from a SegmentAllocator and cached locally.

使用双缓冲号段模式生成ID以实现高性能。 号段从SegmentAllocator获取并在本地缓存。

Double Buffering | 双缓冲:

Buffer1: [1, 1000] → Currently using
Buffer2: [1001, 2000] → Preloaded

When Buffer1 reaches 20%, async load Buffer2

Features | 主要功能:

  • Double buffering - 双缓冲
  • Async preloading - 异步预加载
  • High throughput - 高吞吐量
  • Sequential IDs - 顺序ID

Usage Examples | 使用示例:

JdbcSegmentAllocator allocator = JdbcSegmentAllocator.create(dataSource);
SegmentIdGenerator gen = SegmentIdGenerator.create(allocator, "order");

long orderId = gen.generate();

// Monitor status
var status = gen.getBufferStatus();
System.out.println("Usage: " + status.usagePercent() + "%");

Performance | 性能特性:

  • ~10M ops/sec single thread - 单线程约10M次/秒
  • ~80M ops/sec with 8 threads - 8线程约80M次/秒

Security | 安全性:

  • Thread-safe: Yes - 线程安全: 是
Since:
JDK 25, opencode-base-id V1.0.0
Author:
Leon Soo www.LeonSoo.com
See Also:
  • Method Details

    • create

      public static SegmentIdGenerator create(SegmentAllocator allocator)
      Creates a generator with default business tag 使用默认业务标识创建生成器
      Parameters:
      allocator - the segment allocator | 号段分配器
      Returns:
      generator | 生成器
    • create

      public static SegmentIdGenerator create(SegmentAllocator allocator, String bizTag)
      Creates a generator with specific business tag 使用指定业务标识创建生成器
      Parameters:
      allocator - the segment allocator | 号段分配器
      bizTag - the business tag | 业务标识
      Returns:
      generator | 生成器
    • generate

      public Long generate()
      Description copied from interface: IdGenerator
      Generates the next ID 生成下一个ID
      Specified by:
      generate in interface IdGenerator<Long>
      Returns:
      generated ID | 生成的ID
    • getBizTag

      public String getBizTag()
      Gets the business tag 获取业务标识
      Returns:
      business tag | 业务标识
    • getBufferStatus

      public SegmentIdGenerator.BufferStatus getBufferStatus()
      Gets the current buffer status 获取当前缓冲区状态
      Returns:
      buffer status | 缓冲区状态
    • getType

      public String getType()
      Description copied from interface: IdGenerator
      Gets the generator type name 获取生成器类型名称
      Specified by:
      getType in interface IdGenerator<Long>
      Returns:
      type name | 类型名称
    • close

      public void close()
      Shuts down the preload executor and releases resources. 关闭预加载执行器并释放资源。
      Specified by:
      close in interface AutoCloseable