Core Java

Java UUID

Introduction:

UUID (Universal Unique Identifier) represents a 128-bit long unique value. It’s also popularly known as GUID (Globally Unique Identifier).

The standard representation of UUID is made up of hexadecimal digits:

533a4559-e55c-18b3-8456-555563322002

And has 36 characters that include four hyphens ‘-‘.

java.util.UUID class in Java represents an immutable UUID.

We can use UUID class for generating a random file name, a session or a transaction id. Another popular usage of UUID is for generating primary key values in the database.

Java UUID class has a method for manipulating the Leach-Salz variant (variant 2). However, its constructor allows for generating any type of UUID:

new UUID(long mostSigBits, long leastSigBits)

UUID Versions and Variants:

A variant determines the layout of the UUID. Let’s take a sample UUID:

533a4559-e55c-18b3-8456-555563322002
xxxxxxxx-xxxx-Bxxx-Axxx-xxxxxxxxxxxx

Here, the value of A represents the variant and is determined by its first three MSBs (Most-Significant bits):

MSB1MSB2MSB3Variant Variant Description
0XX0Reserved for NCS backward compatibility
10X2Leach-Salz
1106Reserved, Microsoft Corporation backward compatibility
117Reserved for future definition

For us, A = 8 (1000), so the first three MSBs are 100. That means our UUID has a variant of 2.

For variant 2 UUIDs, there’re five different versions:

VersionDescription
v1time-based
v2DCE- Security
v3 and v5name-based
v4Randomly generated UUID

Generating a UUID:

Let’s cover the methods in the Java UUID class which we can use to generate the UUID:

1. randomUUID():

It generates a v4 pseudo-random UUID using a cryptographically strong pseudo-random number generator:

UUID uuid = UUID.randomUUID();

2. nameUUIDFromBytes():

We can generate a UUID from a byte array using nameUUIDFromBytes():

byte[] byteArr = {11, 23, 33}; 
UUID uuid = UUID.nameUUIDFromBytes(byteArr);

This method generates a v3 UUID (name-based).

3. fromString():

With fromString(), we can create a UUID from a standard string representation:

UUID uuid = UUID.fromString("533a4559-e55c-18b3-2456-555563322002");

It’ll throw an IllegalArgumentException for any invalid string passed in as an argument.

Comparing two UUIDs:

Java UUID class implements Comparable interface. So, we can use the compareTo() method to compare them:

UUID uuid1 = UUID.randomUUID();
UUID uuid2 = UUID.randomUUID();

int result = uuid1.compareTo(uuid2);

As we know, the compareTo() method returns:

  • 1: if uuid1 is greater than uuid2
  • 0: if uuid1 = uuid2
  • -1: if uuid1 is less than that of uuid2

We can optionally use the equals() method for comparison as well.

Other Methods:

Let’s cover a few other methods of the Java UUID class:

1. getLeastSignificantBits() And getMostSignificantBits():

As the name suggests, getLeastSignificantBits() and getMostSignificantBits() return the 64 least-significant and 64 most-significant bits respectively:

UUID uuid = UUID.randomUUID();

long leastSignificantBits = uuid.getLeastSignificantBits();
long mostSignificantBits = uuid.getMostSignificantBits();

Both of these methods return a long value.

2. variant() And version():

We can also query the variant and the version of a UUID:

UUID uuid = UUID.randomUUID();

int variant = uuid.variant();
int version = uuid.version();

Working with a Time-Based UUID (v1):

Let’s start by adding a dependency to java-uuid-generator in our POM:

<dependency>
    <groupId>com.fasterxml.uuid</groupId>
    <artifactId>java-uuid-generator</artifactId>
    <version>3.1.5</version>
</dependency>

Note that this library provides various types of UUID generators.

To create a time-based UUID, we’ll have:

UUID uuid = Generators.timeBasedGenerator().generate();

Other methods from the java.util package that comes handy when dealing with v1 UUIDs’ include:

1. timestamp(): Returns a timestamp value associated with a given v1 UUID. This method will throw a UnsupportedOperationException when used with any other types of UUID.

2. clockSequence(): It returns a 14-bit value constructed from the clock sequence field of a given UUID. It’ll also throw an UnsupportedOperationException for UUIDs other than of type v1.

Conclusion:

In this tutorial, we learned about what a UUID is and its variants. We talked about different available versions for the variant type 2. We also covered a lot of methods exposed by the Java UUID class.

 

Be the First to comment.

Leave a Comment

Your email address will not be published. Required fields are marked *