Skip to main content

On This Page

Generate Valid and Unique Identifiers

2 min read
Share

These articles are AI-generated summaries. Please check the original sources for full details.

Generate Valid and Unique Identifiers

This article details methods for creating unique identifiers in Java, essential for tasks like API keys and short links. Modern applications often require these identifiers to meet specific constraints, such as length and character set, while ensuring they are both random and unique.

Why This Matters

Ideal identifier generation assumes infinite randomness, but practical implementations face collision risks. A UUID has a 50% collision chance after generating 2.71 quintillion IDs, highlighting the importance of robust uniqueness checks, especially in high-scale systems where collisions can lead to data corruption or service disruption.

Key Insights

  • SecureRandom over Random, 2025: Cryptographically strong random number generation is crucial for non-guessable IDs.
  • UUID collision probability: IETF RFC 4122 states a 50% collision chance after generating 2.71 ×10¹⁸ UUIDs.
  • Timestamp-based IDs: Offer performance benefits but lack true randomness and may reveal generation order.

Working Example

import java.security.SecureRandom;
import java.util.Set;
import java.util.stream.Collectors;

public class UniqueIdGenerator {
    private static final String ALPHANUMERIC_CHARACTERS =
            "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    private static final SecureRandom random = new SecureRandom();
    private static int idLength = 8; //Default to be overridden

    public void setIdLength(int idLength) {
        this.idLength = idLength;
    }

    public String generateUniqueId(Set<String> existingIds) {
        String newId;
        do {
            newId = generateRandomString(this.idLength);
        } while (existingIds.contains(newId));
        return newId;
    }

    private String generateRandomString(int length) {
        return random.ints(length, 0, ALPHANUMERIC_CHARACTERS.length())
                .mapToObj(ALPHANUMERIC_CHARACTERS::charAt)
                .map(Object::toString)
                .collect(Collectors.joining());
    }
}

Practical Applications

  • E-commerce (Amazon): Uses UUIDs for order IDs to ensure global uniqueness across millions of transactions.
  • API Key Generation (Stripe): Requires cryptographically secure random strings to prevent unauthorized access.

References:

Continue reading

Next article

AI's Role in Fostering Community Dialogue and Decision-Making

Related Content