Class SnowflakeIdGenerator

java.lang.Object
com.loomcache.server.datastructures.SnowflakeIdGenerator

public class SnowflakeIdGenerator extends Object
Distributed ID generator using Snowflake-like 64-bit ID format.

ID Structure (63 payload bits plus reserved sign bit):

  • 41 bits: timestamp (milliseconds since epoch)
  • 10 bits: nodeId (0-1023, differentiates across cluster)
  • 12 bits: sequence number (0-4095, differentiates within same millisecond)

Features:

  • Globally unique across cluster nodes (nodeId differentiation)
  • Monotonically increasing within a single node
  • Thread-safe with AtomicLong sequence counter
  • Clock rollback protection with wait or throw semantics
  • Optimized batch generation: nextBatch(batchSize), nextBatchAsList(batchSize)
  • Utilities to extract timestamp and nodeId from IDs
Since:
1.2
  • Field Details

  • Constructor Details

    • SnowflakeIdGenerator

      public SnowflakeIdGenerator(String name, int nodeId, int instanceNumber)
  • Method Details

    • newId

      public long newId()
      Generate the next globally unique ID.

      IDs are guaranteed to be:

      • Globally unique across the cluster (different nodeIds)
      • Monotonically increasing on a single node
      • Sortable by timestamp
      Returns:
      the next 64-bit ID
      Throws:
      SnowflakeIdGenerator.ClockRollbackException - if system clock has rolled backwards
    • nextBatch

      public long[] nextBatch(int batchSize)
      Generate a batch of N globally unique IDs as a primitive array.

      More efficient than calling newId() N times because the lock is acquired once for the entire batch, eliminating per-ID lock acquisition overhead. The batch is atomic: no other thread can interleave IDs during generation.

      All IDs in the returned array are guaranteed to be:

      • Globally unique across the cluster
      • Monotonically increasing (array[i] < array[i+1])
      • Non-overlapping with IDs from concurrent newId() calls
      Parameters:
      batchSize - number of IDs to generate (1 to 10,000 inclusive)
      Returns:
      array of batchSize unique, monotonically increasing IDs
      Throws:
      IllegalArgumentException - if batchSize is outside [1, 10000]
      SnowflakeIdGenerator.ClockRollbackException - if system clock has rolled backwards
    • nextBatchAsList

      public List<Long> nextBatchAsList(int batchSize)
      Generate a batch of N globally unique IDs as an unmodifiable list.

      Convenience wrapper around nextBatch(int) that returns a List. See nextBatch(int) for atomicity and ordering guarantees.

      Parameters:
      batchSize - number of IDs to generate (1 to 10,000 inclusive)
      Returns:
      unmodifiable list of batchSize unique, monotonically increasing IDs
      Throws:
      IllegalArgumentException - if batchSize is outside [1, 10000]
      SnowflakeIdGenerator.ClockRollbackException - if system clock has rolled backwards
    • newIdBatch

      @Deprecated(since="1.2", forRemoval=true) public List<Long> newIdBatch(int count)
      Deprecated, for removal: This API element is subject to removal in a future version.
      Use nextBatch(int) or nextBatchAsList(int) instead, which enforce an upper bound (10,000) and hold the lock for the full batch.
      Generate a batch of N globally unique IDs efficiently.

      More efficient than calling newId() N times because it amortizes the overhead of timestamp fetching over multiple IDs.

      Parameters:
      count - number of IDs to generate (must be > 0)
      Returns:
      unmodifiable list of N unique IDs
      Throws:
      IllegalArgumentException - if count <= 0
    • extractTimestamp

      public static long extractTimestamp(long id)
      Extract the timestamp component from a Snowflake ID.

      Returns milliseconds since the custom epoch (January 1, 2020).

      Parameters:
      id - the Snowflake ID
      Returns:
      the timestamp portion (41 bits)
    • extractNodeId

      public static int extractNodeId(long id)
      Extract the node ID component from a Snowflake ID.
      Parameters:
      id - the Snowflake ID
      Returns:
      the node identifier portion (10 bits, 0-1023)
    • extractSequence

      public static int extractSequence(long id)
      Extract the sequence number component from a Snowflake ID.
      Parameters:
      id - the Snowflake ID
      Returns:
      the sequence number portion (12 bits, 0-4095)
    • getCurrentSequence

      public long getCurrentSequence()
      Get the current sequence counter value.

      For diagnostics only. The value is only meaningful within a single millisecond window and will be reset when the timestamp advances.

      Returns:
      the current sequence counter
    • hasGeneratedIds

      public boolean hasGeneratedIds()
    • toSnapshot

      public HashMap<String,Long> toSnapshot()
      Export local generator progress for snapshot persistence.

      The node id is intentionally not persisted: every replica restores the same logical progress using its own configured node id so future failover continues in a disjoint Snowflake node-id space.

    • restoreFromSnapshot

      public void restoreFromSnapshot(long restoredLastTimestamp, long restoredSequence)