Skip to main content

Searching...

Tools
Articles
View All Results

Developer Lab · Java

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

Production Ready
java
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)

java
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

java
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+)

java
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

java
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

java
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

java
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, Performance, and Security

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.

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.

Installation

UUID v4 (java.util.UUID)

bash
// 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.

Frequently Asked Questions

How do I generate a UUID in Java?

Java ships java.util.UUID in the standard library. Call UUID.randomUUID() for a cryptographically random v4 UUID (backed by SecureRandom) and .toString() for the canonical form. The JDK has no built-in v7, so use a library such as java-uuid-generator (com.fasterxml.uuid) for time-ordered UUIDs.

Is UUID.randomUUID() cryptographically secure?

Yes. UUID.randomUUID() uses the platform CSPRNG (operating system secure random source), suitable for session tokens, API keys, and idempotency keys. Do not use non-cryptographic random sources for security-sensitive identifiers.

What is the difference between UUID v4 and v7 in Java?

UUID v4 (UUID.randomUUID() or equivalent) is fully random and not sortable. UUID v7 embeds a millisecond timestamp for chronological sorting (RFC 9562). Use v4 for general-purpose IDs; use v7 for database primary keys at scale.

Do I need to install a package for UUID generation in Java?

No additional package is required for basic v4 generation in Java. Check the Installation section for version-specific notes.

How do I validate a UUID string in Java?

Use the platform's UUID parse/validation function, or test against the RFC 4122 regex: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i. Always validate external input at API boundaries.

Should I use UUIDs as database primary keys in Java applications?

UUIDs work well as primary keys for distributed systems. Prefer native UUID/BINARY(16) column types over VARCHAR(36). For very large tables, consider UUID v7 for better B-tree insert locality.

Can I generate UUIDs in Java without a network connection?

Yes. UUID generation uses local OS entropy sources and does not require network access. Each call is independent and thread-safe on modern platforms.

What output formats are available in Java?

The standard hyphenated lowercase string (36 chars) is the default. Most APIs also support 32-char hex (no hyphens) and 16-byte binary formats. Use string format for APIs and binary for database storage.

What RFC standards apply to Java UUID generation?

Version 4 UUIDs follow RFC 4122. UUID v7 follows RFC 9562 (May 2024). Ensure your chosen method produces compliant version and variant bits.

When should I avoid UUID v1?

Avoid UUID v1 in security-sensitive contexts - it embeds MAC address and timestamp information. Prefer v4 (UUID.randomUUID() or equivalent) unless you need legacy Cassandra timeuuid compatibility.

Key definitions

UUID
128-bit universally unique identifier, usually shown as 36 hex characters with hyphens.
CSPRNG
Cryptographically secure pseudo-random number generator - the entropy source behind secure UUID generation.
RFC 4122
IETF standard defining UUID versions 1 through 5. Version 4 is random.
RFC 9562
IETF standard adding UUID versions 6, 7, and 8. Version 7 is time-ordered.