How do I create a unique ID in Java?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
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:
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:
How it works:
AtomicIntegerprovides atomic operations, which means that theincrementAndGet()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:
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.
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:
| Method | Description | Thread Safety | Example Output |
java.util.UUID | Randomly generated UUID. | Yes | f47ac10b-58cc-4372-a567-0e02b2c3d479 |
AtomicInteger / AtomicLong | Atomically incremented integer. | Yes | Integer: 1, 2, 3, ... |
| Timestamp with Counter | Combines current time with a counter. | No (additional synchronization required) for thread safety | 16184928450001 |
| Apache Commons Lang | Generates random alphanumeric strings. | No | 8JGHD937FH |
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.
Related reading
- How do I create an immutable Class?
- How do I create beans programmatically in Spring Boot?
- How do I decompile Java class files?
- How do I define a method which takes a lambda as a parameter in Java 8?
- How Do I Document Packages in Java?
- How do I enable index downloads in Eclipse for Maven dependency search?
- How do I exclude all instances of a transitive dependency when using Gradle?
- How do I find out what keystore my JVM is using?

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.