Class TimestampSequencer

java.lang.Object
me.ahoo.cosid.internal.TimestampSequencer

public final class TimestampSequencer extends Object
The timestamp and sequence logic shared by the snowflake and CosId generators.

Internal: not part of the CosId API, it may change in any release.

Within one time unit the sequence increments; when it wraps around, next() waits for the next time unit. When a new time unit starts and the sequence has passed sequenceResetThreshold, it restarts from 1, which keeps low-traffic ids from all ending in the same sequence values. A clock that moved backwards throws ClockBackwardsException. Not thread-safe: callers synchronize.

  • Constructor Details

    • TimestampSequencer

      public TimestampSequencer(LongSupplier timeSource, long maxSequence, long sequenceResetThreshold)
      Create a sequencer.
      Parameters:
      timeSource - current time in the generator's unit (milliseconds or seconds)
      maxSequence - largest sequence, a power of two minus one
      sequenceResetThreshold - sequences at or above this restart in the next time unit
  • Method Details

    • next

      public long next()
      Advance to the next (timestamp, sequence) pair; read it with getLastTimestamp() and getSequence().
      Returns:
      the timestamp of the new pair
      Throws:
      ClockBackwardsException - if the clock moved back behind the last timestamp
    • getSequence

      public long getSequence()
    • getLastTimestamp

      public long getLastTimestamp()