How to generate a UUID in Java
UUID.randomUUID() from java.util returns a secure random UUID v4 — built into the JDK since Java 5. All snippets below were verified on JDK 21.
By the Withuse team · Updated
The one-liner
import java.util.UUID; UUID id = UUID.randomUUID(); id.toString(); // "3ec0e96d-6879-4251-baab-480a929558ad" id.version(); // 4
Parsing and validating
UUID u = UUID.fromString("550e8400-e29b-41d4-a716-446655440000");
u.version(); // 4
u.getMostSignificantBits(); // 0x550e8400e29b41d4
u.getLeastSignificantBits(); // 0xa716446655440000
// Invalid input throws IllegalArgumentException — wrap for validation:
static boolean isValidUuid(String s) {
try { UUID.fromString(s); return true; }
catch (IllegalArgumentException e) { return false; }
}One caution: historic JDK versions accepted some malformed strings in fromString; if you validate untrusted input strictly, pair it with a UUID regex check.
The nameUUIDFromBytes trap: it's v3, not v5
UUID v3 = UUID.nameUUIDFromBytes("example.com".getBytes(StandardCharsets.UTF_8));
// 5ababd60-3b22-3803-82dd-8d83498e5172 ← version() == 3 (MD5)The JDK's only name-based generator is v3 (MD5) — and it doesn't take a namespace parameter, so its output won't match uuid5/uuid3 results from Python or JavaScript unless you prepend the namespace bytes yourself. For cross-language deterministic IDs, use a library with proper RFC v5 support.
UUID v7 in Java (library required)
<!-- Maven: java-uuid-generator --> <dependency> <groupId>com.fasterxml.uuid</groupId> <artifactId>java-uuid-generator</artifactId> <version>5.1.0</version> </dependency> import com.fasterxml.uuid.Generators; UUID v7 = Generators.timeBasedEpochGenerator().generate(); // UUID v7
Time-ordered v7 keys keep database indexes append-mostly — the reasoning is in UUID v4 vs v7. Alternative library: uuid-creator (UuidCreator.getTimeOrderedEpoch()).
JPA / Hibernate primary keys
import jakarta.persistence.*;
import java.util.UUID;
@Entity
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.UUID) // JPA 3.1+ / Hibernate 6
private UUID id;
}On PostgreSQL this maps to the native uuid column type (details). For v7 keys, assign the ID yourself in the constructor with a v7 generator instead of @GeneratedValue.
Performance note: SecureRandom
randomUUID() draws from a shared SecureRandom. That's the right default — don't replace it with Random (predictable IDs). Under very high concurrency the shared instance can contend; high-throughput services sometimes use per-thread generators from the libraries above, which also removes the contention.
Frequently asked questions
How do I generate a random UUID in Java?
Call java.util.UUID.randomUUID(). It has been in the JDK since Java 5, needs no dependency, and returns a version 4 UUID whose 122 random bits come from SecureRandom, so the value is cryptographically unpredictable rather than merely unique. The returned object is immutable and safe to share between threads. Use toString() when you need the canonical 36-character form for logs or an API response, and getMostSignificantBits() with getLeastSignificantBits() when you want the raw 128 bits for binary storage. If the identifier is destined to be a database primary key, consider generating v7 through a library instead: v4 values are uniformly random, which scatters inserts across the index, while v7 values sort by creation time and keep writes append-mostly.
Does Java support UUID v5 or v7 natively?
No. The JDK generates only version 4 through randomUUID() and version 3 through nameUUIDFromBytes(), and it can parse any version through fromString(). There is no built-in v5 and no built-in v7. For time-ordered v7 the common choices are java-uuid-generator, where Generators.timeBasedEpochGenerator().generate() returns a v7 value, and uuid-creator, which exposes UuidCreator.getTimeOrderedEpoch(). Both also implement v5 correctly, taking an explicit namespace argument. That namespace parameter is the reason to prefer a library over the JDK for name-based UUIDs: nameUUIDFromBytes() has no namespace concept at all, so its output will not match the v3 or v5 values that Python, JavaScript or PostgreSQL produce for what looks like the same input.
Is UUID.randomUUID() thread-safe?
Yes. UUID instances are immutable and randomUUID() may be called from any thread without external synchronisation. The nuance is throughput rather than correctness: the method lazily initialises a single shared SecureRandom instance, and under heavy concurrent load many threads contending for that one generator can become a measurable bottleneck. Services generating identifiers in a hot loop sometimes address this with a per-thread generator, which the third-party UUID libraries provide, or by moving to v7 generation where the timestamp supplies part of the value and less randomness is drawn per call. Do not solve it by substituting java.util.Random — that generator is predictable from prior output and would turn your identifiers into guessable values.
How do I use a UUID as a JPA or Hibernate primary key?
Declare the field as java.util.UUID and annotate it with @Id and @GeneratedValue(strategy = GenerationType.UUID), which JPA 3.1 and Hibernate 6 support directly; on PostgreSQL the field maps to the native uuid column type, which stores 16 bytes rather than the 36 characters a varchar would need. If you want time-ordered v7 keys instead of the random v4 that GenerationType.UUID produces, drop @GeneratedValue and assign the identifier yourself in the entity constructor using a v7 generator. Doing so also has a practical benefit with Hibernate: an entity that already carries its identifier before persist() behaves predictably in equals and hashCode, which is a recurring source of subtle bugs with database-assigned keys.
Need quick test UUIDs without a REPL? Our free UUID generator makes up to 1,000 at once, any version, in your browser.