Class UuidV7Generator

java.lang.Object
me.ahoo.cosid.time.UuidV7Generator
All Implemented Interfaces:
Supplier<String>

public final class UuidV7Generator extends Object implements Supplier<String>
UUIDv7 ids (D46, RFC 9562 §5.7): a 48-bit Unix millisecond timestamp, version 7, a 16-bit counter (the 12 bits of rand_a and the top 4 bits of rand_b), variant 0b10 and 58 random bits. It needs no machine, namespace or lease: ids are unique without coordination through their random counter start and random bits.

Ordered by method 1 of RFC 9562 §6.2, with a dedicated 16-bit counter (the RFC allows 12 to 42 bits): it starts at a random value below 215 in each millisecond, which leaves at least 215 (32 768) ids per millisecond, and the millisecond and the counter move together in one AtomicLong, 48 + 16 bits. The ids of one instance therefore strictly increase, as UUIDs and as text. The timestamp runs ahead of the clock in two cases only: more than 215 ids in one millisecond, kept up (a full counter carries into the next millisecond), and a clock that goes back (the last timestamp is kept and the counter goes on until the clock catches up). Ids of different instances or processes are ordered by their millisecond only.

The random bits come from ThreadLocalRandom: the ids are unique, not unpredictable. An id is no secret: never use one as a token.

Its public constructors are the assembly entry CosIdRuntime uses (R2-core-03): they keep their signatures, and a new parameter comes only through a builder or a static factory, never as one more positional overload (api-freeze.md §4.2).

  • Constructor Details

    • UuidV7Generator

      public UuidV7Generator(String name, TimeSource time)
      A generator on a time source.
      Parameters:
      name - the generator name, for messages
      time - the time source; TimeSource.SYSTEM outside tests
  • Method Details

    • name

      public String name()
      The generator name.
      Returns:
      the name
    • generateUuid

      public UUID generateUuid()
      The next id.
      Returns:
      a version 7, variant 2 UUID, greater than every id this instance issued before
      Throws:
      TimeOverflowException - if the timestamp passes 48 bits (the year 10889)
    • generate

      public String generate()
      The next id as text.
      Returns:
      the canonical 36-character form, lower case
    • get

      public String get()
      The next id as text: generate().
      Specified by:
      get in interface Supplier<String>
      Returns:
      the canonical form
    • toString

      public String toString()
      Overrides:
      toString in class Object