Generate UUID in Java
Java ships java.util.UUID in the standard library since Java 1.5 — zero dependencies. UUID.randomUUID() gives you a SecureRandom-backed v4 UUID in one line.
Quick Reference
| Method | Version | Sortable | Use Case |
|---|---|---|---|
| UUID.randomUUID() | v4 | No | General purpose — session IDs, record IDs, API keys |
| UUID.nameUUIDFromBytes() | v3 | No | Deterministic — MD5 namespace hash |
| UUID.fromString() | any | — | Parse and validate an existing UUID string |
Primary Implementation
import java.util.UUID;
public class UUIDExample {
public static void main(String[] args) {
// UUID v4 — random, SecureRandom-backed, zero dependencies
UUID id = UUID.randomUUID();
System.out.println(id);
// → f47ac10b-58cc-4372-a567-0e02b2c3d479
// As a string
String idStr = id.toString();
// As two long values (most/least significant bits)
long msb = id.getMostSignificantBits();
long lsb = id.getLeastSignificantBits();
// Parse and validate an existing UUID string
try {
UUID parsed = UUID.fromString("f47ac10b-58cc-4372-a567-0e02b2c3d479");
System.out.println("Version: " + parsed.version()); // → 4
} catch (IllegalArgumentException e) {
System.err.println("Invalid UUID: " + e.getMessage());
}
// Generate multiple UUIDs
List<UUID> ids = IntStream.range(0, 5)
.mapToObj(i -> UUID.randomUUID())
.collect(Collectors.toList());
}
}
All UUID Versions
UUID v4 — Random (recommended default)
import java.util.UUID; // 122 bits of randomness — SecureRandom-backed UUID id = UUID.randomUUID(); System.out.println(id.toString()); // → "550e8400-e29b-41d4-a716-446655440000"
UUID v3 — Deterministic / MD5 Namespace
import java.util.UUID; import java.nio.charset.StandardCharsets; // MD5 hash of namespace bytes + name — same inputs always produce the same UUID // Prefer v5 (SHA-1) when possible; Java stdlib only provides v3 byte[] nameBytes = "example.com".getBytes(StandardCharsets.UTF_8); UUID id = UUID.nameUUIDFromBytes(nameBytes); System.out.println(id);
Spring Boot JPA — UUID primary key (JPA 3.1+)
import jakarta.persistence.*;
import java.util.UUID;
@Entity
public class Order {
// JPA 3.1+ (Spring Boot 3+): auto-generates UUID v4 via SecureRandom
@Id
@GeneratedValue(strategy = GenerationType.UUID)
private UUID id;
private String customerName;
// getters, setters...
}
Real-World Use Cases
1. Spring Boot REST API — request tracing
import org.springframework.web.filter.OncePerRequestFilter;
import jakarta.servlet.http.*;
import java.util.UUID;
public class RequestIdFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest req,
HttpServletResponse res,
FilterChain chain)
throws IOException, ServletException {
String requestId = UUID.randomUUID().toString();
req.setAttribute("requestId", requestId);
res.setHeader("X-Request-ID", requestId);
chain.doFilter(req, res);
}
}
2. Hibernate entity with UUID PK
import org.hibernate.annotations.UuidGenerator;
import jakarta.persistence.*;
import java.util.UUID;
@Entity
@Table(name = "products")
public class Product {
@Id
@UuidGenerator // Hibernate 6+ — generates UUID v4 automatically
@Column(columnDefinition = "uuid", updatable = false, nullable = false)
private UUID id;
private String name;
private BigDecimal price;
}
3. Kafka message ID for deduplication
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.messaging.support.MessageBuilder;
import java.util.UUID;
@Service
public class OrderEventPublisher {
private final KafkaTemplate<String, OrderEvent> kafkaTemplate;
public void publish(OrderEvent event) {
String messageId = UUID.randomUUID().toString();
kafkaTemplate.send(
MessageBuilder.withPayload(event)
.setHeader("messageId", messageId)
.build()
);
}
}
Common Mistakes
Calling UUID.randomUUID().toString() in hot loops
Each .toString() call allocates a new String object. In tight loops, store the UUID object and convert to string only when needed (e.g., at the DB write boundary).
Not using JPA UUID support in Spring Boot 3+
Manually setting @PrePersist to assign a UUID is unnecessary in Spring Boot 3+ (JPA 3.1). Use @GeneratedValue(strategy = GenerationType.UUID) or Hibernate's @UuidGenerator.
Storing UUIDs as VARCHAR(36) in the database
Use the native UUID column type in PostgreSQL or BINARY(16) in MySQL. VARCHAR(36) wastes 20 bytes per row and slows index lookups.
How It Works
UUID.randomUUID() uses SecureRandom internally to generate 16 random bytes, then sets the version bits (4) and variant bits (RFC 4122) before constructing the UUID object.
SecureRandom is thread-safe and seeded from the OS entropy pool. The UUID class is immutable and implements Comparable<UUID> and Serializable.
The internal representation is two long values (most/least significant bits), making it compact and efficient for in-memory use.
Output Formats
id.toString()
f47ac10b-58cc-4372-a567-0e02b2c3d479
No hyphens
id.toString().replace("-", "")
getMostSignificantBits()
-838985819768550542L
getLeastSignificantBits()
-6521180012823431049L
Best Practices
Store UUID objects in memory — only call .toString() at API/DB boundaries.
Use @GeneratedValue(strategy = GenerationType.UUID) in Spring Boot 3+ entities.
Wrap UUID.fromString() in a try-catch — it throws IllegalArgumentException on invalid input.
Performance
Java generates roughly 2–5 million UUIDs/second on modern hardware. SecureRandom is thread-safe and uses a shared instance internally.
The UUID object itself is 32 bytes on the heap (two longs + object header). For bulk generation, consider batching DB inserts rather than generating UUIDs in a tight loop.
Installation
// No installation needed — java.util.UUID
// is part of the Java standard library since Java 1.5
Available in all Java versions from 1.5 onwards. No Maven/Gradle dependency required.
Security
Entropy source: SecureRandom — seeded from the OS entropy pool (/dev/urandom on Linux, CryptGenRandom on Windows). Cryptographically secure.
Suitable for session tokens, CSRF tokens, and API keys. SecureRandom is thread-safe — no synchronization needed.