Understanding Java's UUID.randomUUID() Implementation
This article examines the inner workings of Java's java.util.UUID class, detailing how UUID.randomUUID() generates version‑4 UUIDs using SecureRandom, the bitwise adjustments for version and variant fields, and the constructor logic that assembles the final 128‑bit identifier.
Introduction
Java's java.util.UUID class provides a convenient way to generate universally unique identifiers. The most common usage is UUID.randomUUID(), which creates a version‑4 (random) UUID.
JDK API for UUID
Example code shows generating a UUID with UUID.randomUUID() and logging it.
public void testUUID() {
log.info("generating UUID : [{}]", UUID.randomUUID());
}The method returns a string like 7e281cab-6b44-4426-bab1-f6a1405201d9 . It uses a version‑4 format where the version and variant bits are set explicitly.
UUID Versions
The JDK supports several UUID versions: version‑1 (time‑based), version‑2 (DCE security), version‑3 (name‑based MD5), version‑4 (random), and version‑5 (name‑based SHA‑1).
randomUUID() Implementation
The method creates a SecureRandom instance, fills a 16‑byte array, then applies bitwise operations to set the version (0x4) and variant (0x8) fields.
public static UUID randomUUID() {
SecureRandom ng = Holder.numberGenerator;
byte[] randomBytes = new byte[16];
ng.nextBytes(randomBytes);
randomBytes[6] &= 0x0f; // clear version
randomBytes[6] |= 0x40; // set to version 4
randomBytes[8] &= 0x3f; // clear variant
randomBytes[8] |= 0x80; // set to IETF variant
return new UUID(randomBytes);
}SecureRandom provides cryptographically strong randomness, unlike java.util.Random.
UUID Constructor
private UUID(byte[] data) {
long msb = 0, lsb = 0;
assert data.length == 16 : "data must be 16 bytes in length";
for (int i = 0; i < 8; i++)
msb = (msb << 8) | (data[i] & 0xff);
for (int i = 8; i < 16; i++)
lsb = (lsb << 8) | (data[i] & 0xff);
this.mostSigBits = msb;
this.leastSigBits = lsb;
}The constructor splits the 16‑byte array into two 64‑bit halves (most and least significant bits) to form the final 128‑bit UUID.
Summary
UUID.randomUUID() generates a version‑4 UUID by obtaining 16 secure random bytes, adjusting specific bits for version and variant, and constructing the identifier from the high and low 64‑bit parts, ensuring high uniqueness suitable for primary keys and object identifiers.
Rare Earth Juejin Tech Community
Juejin, a tech community that helps developers grow.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.