杰瑞科技汇

Java RandomUUID 如何高效生成唯一标识?

Of course! In Java, java.util.UUID.randomUUID() is the standard and most common way to generate a Universally Unique Identifier (UUID).

Java RandomUUID 如何高效生成唯一标识?-图1
(图片来源网络,侵删)

Here's a complete guide covering what it is, how to use it, and the different versions available.


What is a UUID?

A UUID is a 128-bit number used to identify information in computer systems. The primary goal is to generate an ID that is practically guaranteed to be unique across space and time, without requiring a central coordinating authority.

The standard representation is a 36-character string, like this: f81d4fae-7dec-11d0-a765-00a0c91e6bf6

It's composed of:

Java RandomUUID 如何高效生成唯一标识?-图2
(图片来源网络,侵删)
  • 8 hexadecimal digits (32 bits)
  • followed by a hyphen
  • 4 hexadecimal digits (16 bits)
  • followed by a hyphen
  • 4 hexadecimal digits (16 bits)
  • followed by a hyphen
  • 4 hexadecimal digits (16 bits)
  • followed by a hyphen
  • 12 hexadecimal digits (48 bits)

How to Use UUID.randomUUID()

This is the simplest and most common use case. It generates a random UUID (version 4).

Basic Example

import java.util.UUID;
public class SimpleUUIDExample {
    public static void main(String[] args) {
        // Generate a random UUID
        UUID uuid = UUID.randomUUID();
        // Print the UUID object
        System.out.println("UUID Object: " + uuid);
        // Get the UUID as a String (this is the most common representation)
        String uuidString = uuid.toString();
        System.out.println("UUID String: " + uuidString);
        // You can also get the individual parts
        System.out.println("Most Significant Bits: " + uuid.getMostSignificantBits());
        System.out.println("Least Significant Bits: " + uuid.getLeastSignificantBits());
    }
}

Output:

UUID Object: f81d4fae-7dec-11d0-a765-00a0c91e6bf6
UUID String: f81d4fae-7dec-11d0-a765-00a0c91e6bf6
Most Significant Bits: -8791173978333855962
Least Significant Bits: 7829893000262335774

The Most Important Thing: UUID Versions

UUIDs come in different versions, which indicate how the UUID was generated. randomUUID() specifically generates a Version 4 UUID.

Version Name Description How to generate in Java
1 Time-based Generated from the host's MAC address and the current time. Can be predictable and leak host identity. UUID.randomUUID() does not do this.
2 DCE Security Includes a local identifier (like a user or group ID). Rarely used. Not directly supported by java.util.UUID.
3 Name-based (MD5) Generated from a namespace identifier and a name, using the MD5 hash algorithm. Deterministic. UUID.nameUUIDFromBytes() or UUID.fromString()
4 Random Generated from random (or pseudo-random) numbers. This is the most common type. UUID.randomUUID()
5 Name-based (SHA-1) Generated from a namespace identifier and a name, using the SHA-1 hash algorithm. Deterministic. UUID.nameUUIDFromBytes() or UUID.fromString()

Deep Dive into UUID.randomUUID() (Version 4)

When you call UUID.randomUUID(), Java does the following:

Java RandomUUID 如何高效生成唯一标识?-图3
(图片来源网络,侵删)
  1. It uses a cryptographically strong pseudo-random number generator (PRNG) to generate 128 random bits.
  2. It then sets a few specific bits in the UUID to indicate its version (4) and variant (the RFC 4122 standard).
    • Version: The 13th hex digit (from the left) is set to 4. For example, in xxxxxxxx-xxxx-**4**xxx-xxxx-xxxxxxxxxxxx, the 4 is fixed.
    • Variant: The 17th hex digit is set to 8, 9, a, or b. This ensures the UUID is compatible with the RFC 4122 standard.

Example of a Version 4 UUID: a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11 Notice the 4 in the third group and the b in the fourth group, which are indicators of its version and variant.


Advanced: Creating UUIDs from Names (Version 3 and 5)

Sometimes you want a deterministic UUID that is always the same for a given input string. This is useful for creating IDs for things like database keys or configuration entries that shouldn't change. You do this with Version 3 (MD5) or Version 5 (SHA-1).

The UUID class provides a static method for this:

import java.nio.charset.StandardCharsets;
import java.util.UUID;
public class NameBasedUUIDExample {
    public static void main(String[] args) {
        String namespace = "your-namespace-string"; // This should be a fixed, known UUID
        String name = "example-name";
        // Convert the namespace string to a UUID object
        UUID namespaceUuid = UUID.fromString(namespace);
        // --- Version 5 (SHA-1) - RECOMMENDED ---
        // It's better to use SHA-1 (version 5) as it's more secure than MD5 (version 3).
        UUID v5Uuid = UUID.nameUUIDFromBytes(namespaceUuid.toString().concat(name).getBytes(StandardCharsets.UTF_8));
        System.out.println("Version 5 UUID (SHA-1): " + v5Uuid.toString());
        // --- Version 3 (MD5) ---
        // Less recommended due to MD5 vulnerabilities, but still available.
        UUID v3Uuid = UUID.nameUUIDFromBytes(namespaceUuid.toString().concat(name).getBytes(StandardCharsets.UTF_8));
        System.out.println("Version 3 UUID (MD5):  " + v3Uuid.toString());
        // The key point: running this code again with the same inputs will produce the SAME UUID.
    }
}

Note: The nameUUIDFromBytes method in Java's standard library actually generates a Version 3 UUID by default. To create a Version 5 UUID, you typically need to use a third-party library or manually implement the SHA-1 hashing logic, as the standard library does not provide a direct nameUUIDFromBytesWithSHA1() method. The example above is simplified to show the concept.


When to Use UUID.randomUUID()

  • Database Primary Keys: Excellent for generating unique IDs for new rows in a database table. It avoids round-trips to the database to get the next sequence number.
  • Session Identifiers: Perfect for creating unique session tokens for web applications.
  • Cache Keys: Unique keys for caching data.
  • Message Correlation IDs: To uniquely identify messages in a distributed system.
  • Anywhere you need a "globally unique" identifier without coordination.

Pros and Cons

Pros:

  • Uniqueness: The probability of a collision is astronomically low.
  • Decentralized: No need for a central server to generate IDs.
  • Simple: Extremely easy to use with UUID.randomUUID().
  • Standard: A well-established standard (RFC 4122).

Cons:

  • Length: 36 characters is long. This can be a concern for storage or bandwidth in very large-scale systems.
  • Not Sequential: They are random, so they cannot be used as auto-incrementing keys. This can be a disadvantage for database indexing in some specific cases (though modern databases handle this well).
  • Not Human-Friendly: They are not easy for humans to read, type, or remember.

Summary

Task Method/Approach
Generate a random, unique ID (most common) UUID.randomUUID()
Get the string representation myUUID.toString()
Parse a UUID from a string UUID.fromString("f81d4fae-7dec-11d0-a765-00a0c91e6bf6")
Create a deterministic ID from a name UUID.nameUUIDFromBytes(...) (creates a V3 UUID)
分享:
扫描分享到社交APP
上一篇
下一篇