UUID Version 7 Time Ordered

Build RFC 9562 version-7 UUIDs from a 48-bit millisecond timestamp so lexicographic order matches creation time, then verify compareTo follows the clock.

JavaData Integrity

Code

snippet
import java.security.SecureRandom;
import java.util.UUID;

public class TimeOrderedIds {

    static final SecureRandom RANDOM = new SecureRandom();

    // 手工构造 UUIDv7(RFC 9562):48 位 unix 毫秒时间戳占据最高位,
    // 字典序 = 时间序;version 位写 0111,variant 位写 10
    static UUID generate(long unixMillis) {
        long mostSig = (unixMillis << 16)              // 48-bit unix millis prefix
                | 0x7000L                              // version 7
                | RANDOM.nextInt(1 << 12);             // rand_a, 12 bits
        long leastSig = (0x2L << 62)                   // variant 10
                | (RANDOM.nextLong() >>> 2);           // rand_b, 62 bits
        return new UUID(mostSig, leastSig);
    }

    public static void main(String[] args) {
        long base = System.currentTimeMillis();
        UUID first = generate(base);
        UUID second = generate(base + 1);
        UUID third = generate(base + 2);

        System.out.println("version of first: " + first.version());
        System.out.println("variant of first: " + first.variant());
        // 时间上的先后与 compareTo 的字典序完全一致
        System.out.println("time order = lex order: "
                + (first.compareTo(second) < 0 && second.compareTo(third) < 0));

        UUID older = generate(base - 10);
        System.out.println("older sorts before newer: " + (older.compareTo(first) < 0));
    }
}

The layout of the snippet

One way to read it: the class TimeOrderedIds and the functions generate and main, doing all the work.

Applying it

The entry-point signature is static UUID generate(long unixMillis)

The run emits 4 labeled sections — version of first:, variant of first:, time order = lex order:, older sorts before newer: — one per step.

The entry point wires generate together — run it once and the whole demo flows.

Statements that matter

return new UUID(mostSig, leastSig);

Interactive Tools for This Topic

FAQ

What does UUID Version 7 Time Ordered print when run?
Run it as a complete program — the output lines carry labels such as `version of first:`, `variant of first:`, `time order = lex order:`.