Class SnowflakeIdGenerator
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
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic classException thrown when system clock rolls backward. -
Field Summary
Fields -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionstatic intextractNodeId(long id) Extract the node ID component from a Snowflake ID.static intextractSequence(long id) Extract the sequence number component from a Snowflake ID.static longextractTimestamp(long id) Extract the timestamp component from a Snowflake ID.longGet the current sequence counter value.booleanlongnewId()Generate the next globally unique ID.newIdBatch(int count) Deprecated, for removal: This API element is subject to removal in a future version.long[]nextBatch(int batchSize) Generate a batch of N globally unique IDs as a primitive array.nextBatchAsList(int batchSize) Generate a batch of N globally unique IDs as an unmodifiable list.voidrestoreFromSnapshot(long restoredLastTimestamp, long restoredSequence) Export local generator progress for snapshot persistence.
-
Field Details
-
MAX_NODE_ID
public static final int MAX_NODE_ID- See Also:
-
-
Constructor Details
-
SnowflakeIdGenerator
-
-
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
batchSizeunique, monotonically increasing IDs - Throws:
IllegalArgumentException- if batchSize is outside [1, 10000]SnowflakeIdGenerator.ClockRollbackException- if system clock has rolled backwards
-
nextBatchAsList
Generate a batch of N globally unique IDs as an unmodifiable list.Convenience wrapper around
nextBatch(int)that returns aList. SeenextBatch(int)for atomicity and ordering guarantees.- Parameters:
batchSize- number of IDs to generate (1 to 10,000 inclusive)- Returns:
- unmodifiable list of
batchSizeunique, monotonically increasing IDs - Throws:
IllegalArgumentException- if batchSize is outside [1, 10000]SnowflakeIdGenerator.ClockRollbackException- if system clock has rolled backwards
-
newIdBatch
Deprecated, for removal: This API element is subject to removal in a future version.UsenextBatch(int)ornextBatchAsList(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
-
restoreFromSnapshot
public void restoreFromSnapshot(long restoredLastTimestamp, long restoredSequence)
-
nextBatch(int)ornextBatchAsList(int)instead, which enforce an upper bound (10,000) and hold the lock for the full batch.