Create a GUID / UUID in Java
To create a UUID in Java swiftly, the java.util.UUID
class provides randomUUID()
:
It yields a UUID that conforms to RFC 4122 Type 4 (pseudo-randomly generated) standard. It's highly unlikely to collide with any existing UUIDs. Need to see it or use it as a string?
Preliminary steps
Ready to dive into the UUID pool? Check your setup:
- You're using Java 5 onwards, right? The
UUID
class is available from there. - Don't forget to import the
java.util.UUID
class in your file.
UUID from Strings and NIL UUIDs
Besides randomness, you can "create" UUIDs from known string values:
The Nil UUID, all zeroes, also has a special birthplace:
RFC 4122 and UUID version saga
You can enquire UUID's version like this:
Java's UUID class meets RFC 4122 standards for universal love across different systems.
More than randomness: UUID anatomy
UUID can be created using different versions based on the strategy to ensure uniqueness:
- Version 1 UUID (MAC address + Time-based): Your ID is where and when you are + NIC :)
- Version 4 UUID (Random): Leave it to Lady Luck
- Version 5 UUID (SHA-1 Hash-based): A hashed mash-up of a namespace identifier and original value
Version 1 UUID in Java
We need an external library (like JUG - Java Uuid Generator). Let's get temporal:
Making Version 5 UUID at Home
Java's UUID doesn't natively create Version 5 UUIDs. We need crypto:
Platforms beyond Java
Turns out, every system has its UUID quirks:
- Command-line: On Mac OS X, BSD, Linux —
uuidgen
is your friend. - Database: Ever heard of functions like
uuid_generate_v4()
in PostgreSQL? - Online: Generators like
uuidgenerator.net
can get you a UUID over HTTP.
Play nice with databases and web services
Need to interact with databases or web services? A UUID has got your back:
- JDBC: Fetch or store UUIDs via Java Database Connectivity.
- Web APIs: A UUID is your ticket to entities on RESTful services.
Advancing UUID usage
Working with external systems
To dunk your UUIDs in different versions that Java's UUID class doesn't natively muster, you may need to adopt alternative libraries or services.
Security aspects with UUID
Version 4 UUID is the best bet when heavy-duty UUID security is a concern. A right random number generator reinforces your UUID castle.
Be smart when storing UUIDs
When storing UUIDs in databases, mind the storage format (binary or string) and the effect on your database index performance.
Was this article helpful?