Java
Unique ID
Programming
Software Development
Java UUID

How do I create a unique ID in Java?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Creating a unique ID in Java is a common requirement in various scenarios, such as session tracking, database primary keys, unique user identifiers, and more. Java offers several ways to generate unique IDs, including the use of UUIDs, atomic integers, and third-party libraries. Here, we delve into these methods with technical explanations and examples.

1. Using java.util.UUID

The UUID class in Java provides a means to generate universally unique identifiers based on the GUID (Globally Unique Identifier) standard.

Example:

java
1import java.util.UUID;
2
3public class UniqueIDExample {
4    public static void main(String[] args) {
5        UUID uniqueID = UUID.randomUUID();  // Generate a random UUID
6        System.out.println("Generated UUID: " + uniqueID.toString());
7    }
8}

How it works:

  • The UUID.randomUUID() method generates a type-4 (pseudo-randomly generated) UUID.
  • The generated UUID has a standard 36-character representation, including hyphens, e.g., f47ac10b-58cc-4372-a567-0e02b2c3d479.

2. Using Atomic Variables for Simple Unique IDs

For scenarios that require simple incrementing numbers as unique IDs, Java's AtomicInteger or AtomicLong can be used. These classes are useful when thread safety is required.

Example:

java
1import java.util.concurrent.atomic.AtomicInteger;
2
3public class AtomicUniqueIDExample {
4    private static AtomicInteger counter = new AtomicInteger(0);
5
6    public static void main(String[] args) {
7        for (int i = 0; i < 5; i++) {
8            int uniqueID = generateUniqueID();
9            System.out.println("Generated Atomic ID: " + uniqueID);
10        }
11    }
12
13    private static int generateUniqueID() {
14        return counter.incrementAndGet();  // Atomically increments and returns the new value
15    }
16}

How it works:

  • AtomicInteger provides atomic operations, which means that the incrementAndGet() method is thread-safe.
  • Each call to incrementAndGet() will atomically increment the counter and provide a unique integer.

3. Using Timestamp with a Counter

Combining the current timestamp with a counter can provide unique IDs at a given point in time.

Example:

java
1public class TimestampIDExample {
2    private static int counter = 0;
3
4    public static void main(String[] args) {
5        synchronized (TimestampIDExample.class) {
6            long uniqueID = generateTimestampID();
7            System.out.println("Generated Timestamp ID: " + uniqueID);
8        }
9    }
10
11    private static long generateTimestampID() {
12        long timestamp = System.currentTimeMillis();
13        return Long.parseLong(timestamp + "" + counter++);
14    }
15}

How it works:

  • System.currentTimeMillis() provides the current time in milliseconds.
  • A separate counter ensures distinct IDs, even if generateTimestampID() is called multiple times within the same millisecond.

4. Third-Party Libraries

Often, external libraries provide more sophisticated solutions for unique ID generation:

Example: Apache Commons Lang

Apache Commons Lang provides a powerful utility called RandomStringUtils.

xml
1<!-- Maven Dependency for Apache Commons Lang -->
2<dependency>
3    <groupId>org.apache.commons</groupId>
4    <artifactId>commons-lang3</artifactId>
5    <version>3.12.0</version>
6</dependency>
java
1import org.apache.commons.lang3.RandomStringUtils;
2
3public class RandomStringExample {
4    public static void main(String[] args) {
5        String randomString = RandomStringUtils.randomAlphanumeric(10); // Generates a 10-character random alphanumeric string
6        System.out.println("Generated Random String: " + randomString);
7    }
8}

How it works:

  • RandomStringUtils.randomAlphanumeric(int count) generates a random string with the specified length composed of alphabetic and numeric characters.

Here is a table summarizing the key points:

MethodDescriptionThread SafetyExample Output
java.util.UUIDRandomly generated UUID.Yesf47ac10b-58cc-4372-a567-0e02b2c3d479
AtomicInteger / AtomicLongAtomically incremented integer.YesInteger: 1, 2, 3, ...
Timestamp with CounterCombines current time with a counter.No (additional synchronization required) for thread safety16184928450001
Apache Commons LangGenerates random alphanumeric strings.No8JGHD937FH

Additional Considerations

Performance and Scalability

  • UUIDs are great for ensuring uniqueness across systems but may not be optimal for performance-critical applications due to their size and randomness.
  • Simple incrementing IDs (using AtomicInteger) can become a bottleneck if not managed properly in concurrent environments.

Use Cases

  • Use UUIDs when global uniqueness is a requirement.
  • Use atomic counters for lightweight, sequential ID generation within a single JVM.
  • Consider third-party libraries for more customized needs such as alphanumeric strings.

In conclusion, Java provides various in-built mechanisms to generate unique IDs, while external libraries offer further flexibility for specific use cases. The choice of method depends on the specific requirements of your application, such as uniqueness, performance, and scalability constraints.


Course illustration
Course illustration

All Rights Reserved.