Class SafeJavaScriptSnowflakeId

java.lang.Object
me.ahoo.cosid.snowflake.SafeJavaScriptSnowflakeId

public final class SafeJavaScriptSnowflakeId extends Object
Safe JavaScript Snowflake ID generators.

JavaScript Numbers can only safely represent integers up to 2^53 - 1 (Number.MAX_SAFE_INTEGER = 9007199254740991). This class provides factory methods for creating SnowflakeId instances that stay within this limit by reducing total bits to 53 or fewer.

  • Field Details

    • JAVA_SCRIPT_MAX_SAFE_NUMBER_BIT

      public static final int JAVA_SCRIPT_MAX_SAFE_NUMBER_BIT
      Maximum safe JavaScript number bit count.
      See Also:
    • JAVA_SCRIPT_MAX_SAFE_NUMBER

      public static final long JAVA_SCRIPT_MAX_SAFE_NUMBER
      Maximum safe JavaScript number value.
      See Also:
  • Constructor Details

    • SafeJavaScriptSnowflakeId

      public SafeJavaScriptSnowflakeId()
  • Method Details

    • isSafeJavaScript

      public static boolean isSafeJavaScript(long id)
      Checks if an ID is safe for JavaScript.
      Parameters:
      id - the ID to check
      Returns:
      true if less than MAX_SAFE_NUMBER
    • ofMillisecond

      public static MillisecondSnowflakeId ofMillisecond(long epoch, int timestampBit, int machineBit, int sequenceBit, int machineId, long sequenceResetThreshold)
      Creates a safe millisecond SnowflakeId.
      Parameters:
      epoch - epoch timestamp
      timestampBit - bits for timestamp
      machineBit - bits for machine ID
      sequenceBit - bits for sequence
      machineId - the machine ID
      sequenceResetThreshold - threshold for sequence reset
      Returns:
      a new MillisecondSnowflakeId
    • ofMillisecond

      public static MillisecondSnowflakeId ofMillisecond(int machineId)
      Creates a safe millisecond SnowflakeId with default safe configuration.

      Default safe configuration:

      • Timestamp: 41 bits
      • Machine: 3 bits
      • Sequence: 9 bits
      Parameters:
      machineId - the machine ID (max 7)
      Returns:
      MillisecondSnowflakeId
    • ofSecond

      public static SecondSnowflakeId ofSecond(long epoch, int timestampBit, int machineBit, int sequenceBit, int machineId, long sequenceResetThreshold)
      Creates a safe second SnowflakeId.
      Parameters:
      epoch - epoch timestamp
      timestampBit - bits for timestamp
      machineBit - bits for machine ID
      sequenceBit - bits for sequence
      machineId - the machine ID
      sequenceResetThreshold - threshold for sequence reset
      Returns:
      a new SecondSnowflakeId
    • ofSecond

      public static SecondSnowflakeId ofSecond(int machineId)
      Creates a safe second SnowflakeId with default safe configuration.

      Default safe configuration:

      • Timestamp: 31 bits
      • Machine: 3 bits
      • Sequence: 19 bits
      Parameters:
      machineId - the machine ID (max 7)
      Returns:
      SecondSnowflakeId