- Time based uuid java
- Notes on the algorithm used to generate time-based UUIDs
- Field Summary
- Method Summary
- Methods inherited from class java.lang.Object
- Field Detail
- PID_SYSTEM_PROPERTY
- Method Detail
- random
- timeBased
- startOf
- endOf
- unixTimestamp
- How to generate time based uuids in Java?
- Method 1: Using the java.util.UUID class
- Method 2: Using the Apache Commons Ids library
- Method 3: Using a third-party library such as Jug
- Time based uuid generator in java (JUG library / example)
- Program: time based uuid generator in java (using JUG library)
- Output: time based uuid generator in java (JUG library)
- You may also like:
- Java UUID
- UUID Versions and Variants:
- Generating a UUID:
- 1. randomUUID():
- 2. nameUUIDFromBytes():
- 3. fromString():
- Comparing two UUIDs:
- Other Methods:
- 1. getLeastSignificantBits() And getMostSignificantBits():
- 2. variant() And version():
- Working with a Time-Based UUID (v1):
- Conclusion:
Time based uuid java
Utility methods to help working with UUIDs, and more specifically, with time-based UUIDs (also known as Version 1 UUIDs).
Notes on the algorithm used to generate time-based UUIDs
- Since Java does not provide direct access to the host’s MAC address, that information is replaced with a digest of all IP addresses available on the host;
- The process ID (PID) isn’t easily available to Java either, so it is determined by one of the following methods, in the order they are listed below:
- If the System property «com.datastax.driver.PID» is set then the value to use as a PID will be read from that property;
- Otherwise, if a native call to getpid() is possible, then the PID will be read from that call;
- Otherwise, an attempt will be made to read the PID from JMX’s RuntimeMXBean , which is a well-known, yet undocumented «hack», since most JVMs tend to use the JVM’s PID as part of that MXBean name;
- If all of the above fails, a random integer will be generated and used as a surrogate PID.
Field Summary
Method Summary
Creates a «fake» time-based UUID that sorts as the biggest possible version 1 UUID generated at the provided timestamp.
Creates a «fake» time-based UUID that sorts as the smallest possible version 1 UUID generated at the provided timestamp.
Methods inherited from class java.lang.Object
Field Detail
PID_SYSTEM_PROPERTY
Method Detail
random
timeBased
Creates a new time-based (version 1) UUID. UUIDs generated by this method are suitable for use with the timeuuid Cassandra type. In particular the generated UUID includes the timestamp of its generation. Note that there is no way to provide your own timestamp. This is deliberate, as we feel that this does not conform to the UUID specification, and therefore don’t want to encourage it through the API. If you want to do it anyway, use the following workaround:
Random random = new Random(); UUID uuid = new UUID(UUIDs.startOf(userProvidedTimestamp).getMostSignificantBits(), random.nextLong());
If you simply need to perform a range query on a timeuuid column, use the «fake» UUID generated by startOf(long) and endOf(long) .
startOf
Creates a «fake» time-based UUID that sorts as the smallest possible version 1 UUID generated at the provided timestamp. Such created UUIDs are useful in queries to select a time range of a timeuuid column. The UUIDs created by this method are not unique and as such are not suitable for anything else than querying a specific time range. In particular, you should not insert such UUIDs. «True» UUIDs from user-provided timestamps are not supported (see timeBased() for more explanations). Also, the timestamp to provide as a parameter must be a Unix timestamp (as returned by System.currentTimeMillis() or Date.getTime() ), and not a count of 100-nanosecond intervals since 00:00:00.00, 15 October 1582 (as required by RFC-4122). In other words, given a UUID uuid , you should never call startOf(uuid.timestamp()) but rather startOf(unixTimestamp(uuid)) . Lastly, please note that Cassandra’s timeuuid sorting is not compatible with UUID.compareTo(java.util.UUID) and hence the UUIDs created by this method are not necessarily lower bound for that latter method.
endOf
Creates a «fake» time-based UUID that sorts as the biggest possible version 1 UUID generated at the provided timestamp. See startOf(long) for explanations about the intended usage of such UUID.
unixTimestamp
Return the Unix timestamp contained by the provided time-based UUID. This method is not equivalent to UUID.timestamp() . More precisely, a version 1 UUID stores a timestamp that represents the number of 100-nanoseconds intervals since midnight, 15 October 1582 and that is what UUID.timestamp() returns. This method however converts that timestamp to the equivalent Unix timestamp in milliseconds, i.e. a timestamp representing a number of milliseconds since midnight, January 1, 1970 UTC. In particular, the timestamps returned by this method are comparable to the timestamps returned by System.currentTimeMillis() , Date.getTime() , etc.
How to generate time based uuids in Java?
UUIDs, or universally unique identifier, are commonly used as a method of generating unique identifiers for entities in a distributed system. Time-based UUIDs are a type of UUID that are generated based on the current time and are guaranteed to be unique across space and time. In Java, there are a number of ways to generate time-based UUIDs, some of which are more efficient or easier to use than others.
Method 1: Using the java.util.UUID class
To generate time-based UUIDs in Java using the java.util.UUID class, you can use the UUID.fromString() method to create a new UUID based on the current time. Here’s an example code snippet:
import java.util.UUID; public class TimeBasedUUIDGenerator public static void main(String[] args) UUID uuid = UUID.fromString("38400000-8cf0-11bd-b23e-10b96e4ef00d"); long time = System.currentTimeMillis(); long timeLow = time & 0xFFFFFFFFL; long timeMid = time & 0xFFFF00000000L; timeMid >>= 16; long timeHi = time & 0xFFF000000000000L; timeHi >>= 48; timeMid |= 0x1000; timeHi |= 0x1000; uuid = new UUID(timeLow, timeMid | timeHi); System.out.println("Time-based UUID: " + uuid.toString()); > >
This code creates a new UUID based on the current time, using the fromString() method to initialize the UUID with a known value. It then extracts the current time in milliseconds, and uses bitwise operations to split the time into the three components of a time-based UUID: time_low, time_mid, and time_hi_and_version. Finally, it combines the three components into a new UUID using the UUID(long, long) constructor.
This is just one example of how to generate time-based UUIDs using the java.util.UUID class. There are many other methods and libraries available for generating UUIDs in Java, so be sure to explore your options and choose the one that best fits your needs.
Method 2: Using the Apache Commons Ids library
To generate time-based UUIDs in Java using the Apache Commons Ids library, follow these steps:
- Add the Apache Commons Ids library to your project’s dependencies. You can do this by adding the following Maven dependency to your project’s pom.xml file:
dependency> groupId>org.apache.commonsgroupId> artifactId>commons-idsartifactId> version>1.0version> dependency>
import org.apache.commons.ids.UUIDGenerator; import org.apache.commons.ids.generator.TimeBasedGenerator;
UUIDGenerator uuidGenerator = new TimeBasedGenerator();
String uuid = uuidGenerator.generate().toString();
Here is the complete code example:
import org.apache.commons.ids.UUIDGenerator; import org.apache.commons.ids.generator.TimeBasedGenerator; public class TimeBasedUUIDGenerator public static void main(String[] args) UUIDGenerator uuidGenerator = new TimeBasedGenerator(); String uuid = uuidGenerator.generate().toString(); System.out.println("Time-based UUID: " + uuid); > >
This code will output a time-based UUID, which is generated using the Apache Commons Ids library.
Method 3: Using a third-party library such as Jug
To generate time-based UUIDs in Java using the Jug library, follow these steps:
dependency> groupId>com.fasterxml.uuidgroupId> artifactId>java-uuid-generatorartifactId> version>4.2.0version> dependency>
import com.fasterxml.uuid.Generators; import com.fasterxml.uuid.impl.TimeBasedGenerator; TimeBasedGenerator uuidGenerator = Generators.timeBasedGenerator();
import java.util.UUID; UUID uuid = uuidGenerator.generate();
String uuidString = uuid.toString();
import com.fasterxml.uuid.Generators; import com.fasterxml.uuid.impl.TimeBasedGenerator; import java.util.UUID; public class Example public static void main(String[] args) TimeBasedGenerator uuidGenerator = Generators.timeBasedGenerator(); UUID uuid = uuidGenerator.generate(); String uuidString = uuid.toString(); System.out.println(uuidString); > >
Time based uuid generator in java (JUG library / example)
Program: time based uuid generator in java (using JUG library)
package org.learn.uuid; import com.fasterxml.uuid.EthernetAddress; import com.fasterxml.uuid.Generators; import com.fasterxml.uuid.NoArgGenerator; import java.util.UUID; public class TimeBasedUUID < public static void main(String[] args) < NoArgGenerator timeBasedGenerator = Generators.timeBasedGenerator(); //Generate time based UUID UUID firstUUID = timeBasedGenerator.generate(); System.out.printf("1. First UUID is : %s ", firstUUID.toString()); System.out.printf("\n2. Timestamp of UUID is : %d ", firstUUID.timestamp()); UUID secondUUID = timeBasedGenerator.generate(); System.out.printf("\n3. Second UUID is :%s ", secondUUID.toString()); System.out.printf("\n4. Timestamp of UUID is : %d ", secondUUID.timestamp()); //Generate custom UUID from network interface timeBasedGenerator = Generators.timeBasedGenerator(EthernetAddress.fromInterface()); UUID customUUID = timeBasedGenerator.generate(); UUID anotherCustomUUID = timeBasedGenerator.generate(); System.out.printf("\n5. Custom UUID is :%s ", customUUID.toString()); System.out.printf("\n6. Another custom UUID : %s ", anotherCustomUUID.toString()); >>
Output: time based uuid generator in java (JUG library)
1. First UUID is : c81d4e2e-bcf2-11e6-869b-7df92533d2db 2. Timestamp of UUID is : 137004589606850094 3. Second UUID is :c81eadbf-bcf2-11e6-869b-7df92533d2db 4. Timestamp of UUID is : 137004589606940095 5. Custom UUID is :c83458a0-bcf2-11e6-869b-e4a7a078fa06 6. Another custom UUID : c83458a1-bcf2-11e6-869b-e4a7a078fa06
You may also like:
Java UUID
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:
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):
MSB1 MSB2 MSB3 Variant Variant Description 0 X X 0 Reserved for NCS backward compatibility 1 0 X 2 Leach-Salz 1 1 0 6 Reserved, Microsoft Corporation backward compatibility 1 1 7 Reserved 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:
Version Description v1 time-based v2 DCE- Security v3 and v5 name-based v4 Randomly generated UUID Generating a UUID:
1. randomUUID():
It generates a v4 pseudo-random UUID using a cryptographically strong pseudo-random number generator:
UUID uuid = UUID.randomUUID();
2. nameUUIDFromBytes():
byte[] byteArr = ; UUID uuid = UUID.nameUUIDFromBytes(byteArr);
3. fromString():
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);
- 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:
com.fasterxml.uuid java-uuid-generator 3.1.5 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.
Published on Java Code Geeks with permission by Shubhra Srivastava, partner at our JCG program. See the original article here: Java UUID