- Generate time based uuid in java using JUG (Java Uuid Generator) library.
- JUG library provides couple of generator viz TimeBasedGenerator & RandomBasedGenerator.
- In current post, we will demonstrate TimeBasedGenerator of JUG library.
- Generate time based UUID using TimeBasedGenerator
- Get the timestamp of generated UUID.
- Generate custom UUID using network interface.
Maven dependency of JUG library
<dependency>
<groupId>com.fasterxml.uuid</groupId>
<artifactId>java-uuid-generator</artifactId>
<version>3.1.3</version>
</dependency>
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