Summary
Add a static factory method UUID.epochMillis(long) to create Version 7 UUIDs as defined in RFC 9562, embedding the supplied Unix time in milliseconds.
Problem
The JDK currently exposes static factories for version 3 (name-based) and version 4 (random) UUIDs via nameUUIDFromBytes() and randomUUID(), respectively. However, there is no built-in support for generating version 7 UUIDs, which incorporate millisecond-precision Unix timestamps and provide lexicographically sortable, time-ordered identifiers. UUIDv7 provides unique identifiers which can be sorted by creation time and has been of increasing popularity especially in distributed systems.
Solution
Introduce a new static factory method in java.util.UUID:
public static UUID epochMillis(long timestamp)
- Generates a Version 7 UUID using the provided Unix epoch timestamp in milliseconds (must fit within 48 bits). The method embeds the timestamp into the first 48 bits, sets the version (7) and IETF variant fields, and fills the remaining bits with cryptographically strong random data.
Specification
Update UUID.java spec with the following:
/**
* Creates a {@code UUIDv7} {@code UUID} from the given Unix Epoch timestamp.
*
* The returned {@code UUID} will have the given {@code timestamp} in
* the first 6 bytes, followed by the version and variant bits representing {@code UUIDv7},
* and the remaining bytes will contain random data from a cryptographically strong
* pseudo-random number generator.
*
* @apiNote {@code UUIDv7} values are created by allocating a Unix timestamp in milliseconds
* in the most significant 48 bits and filling the remaining 74 bits, excluding the required
* version and variant bits, with random bits. As such, this method rejects {@code timestamp}
* values that do not fit into 48 bits.
* <p>
* Monotonicity (each subsequent value being greater than the last) is a primary characteristic
* of {@code UUIDv7} values. This is due to the {@code timestamp} value being part of the {@code UUID}.
* Callers of this method that wish to generate monotonic {@code UUIDv7} values are expected to
* ensure that the given {@code timestamp} value is monotonic.
*
*
* @param timestamp the number of milliseconds since midnight 1 Jan 1970 UTC,
* leap seconds excluded.
*
* @return a {@code UUID} constructed using the given {@code timestamp}
*
* @throws IllegalArgumentException if the timestamp is negative or greater than {@code 281474976710655L}
*
* @spec https://www.rfc-editor.org/rfc/rfc9562.html
* RFC 9562 Universally Unique IDentifiers (UUIDs)
*
* @since 26
*
*/
public static UUID epochMillis(long timestamp) {...}
- csr of
-
JDK-8334015 Add Support for UUID Version 7 (UUIDv7) defined in RFC 9562
-
- Open
-