A UUID is 36 characters long unique number. It is also known as a Globally Unique Identifier (GUID). A UUID is a class that represents an immutable Universally Unique Identifier (UUID). A UUID represents a 128-bit long value that is unique to all practical purpose.
From the documentation and wikipedia we see that randomUUID is good - but there is a very small chance that duplicates can be generated.
Create a UUID.
String uniqueID = UUID.randomUUID().toString();
If you want short, human-readable IDs and only need them to be unique per JVM run:
private static long idCounter = 0;
public static synchronized String createID()
{
return String.valueOf(idCounter++);
}
Edit: Alternative suggested in the comments - this relies on under-the-hood "magic" for thread safety, but is more scalable and just as safe:
private static AtomicLong idCounter = new AtomicLong();
public static String createID()
{
return String.valueOf(idCounter.getAndIncrement());
}
java.util.UUID
: toString() method
Here's my two cent's worth: I've previously implemented an IdFactory
class that created IDs in the format [host name]-[application start time]-[current time]-[discriminator]. This largely guaranteed that IDs were unique across JVM instances whilst keeping the IDs readable (albeit quite long). Here's the code in case it's of any use:
public class IdFactoryImpl implements IdFactory {
private final String hostName;
private final long creationTimeMillis;
private long lastTimeMillis;
private long discriminator;
public IdFactoryImpl() throws UnknownHostException {
this.hostName = InetAddress.getLocalHost().getHostAddress();
this.creationTimeMillis = System.currentTimeMillis();
this.lastTimeMillis = creationTimeMillis;
}
public synchronized Serializable createId() {
String id;
long now = System.currentTimeMillis();
if (now == lastTimeMillis) {
++discriminator;
} else {
discriminator = 0;
}
// creationTimeMillis used to prevent multiple instances of the JVM
// running on the same host returning clashing IDs.
// The only way a clash could occur is if the applications started at
// exactly the same time.
id = String.format("%s-%d-%d-%d", hostName, creationTimeMillis, now, discriminator);
lastTimeMillis = now;
return id;
}
public static void main(String[] args) throws UnknownHostException {
IdFactory fact = new IdFactoryImpl();
for (int i=0; i<1000; ++i) {
System.err.println(fact.createId());
}
}
}
Generate Unique ID Using Java
UUID is the fastest and easiest way to generate unique ID in Java.
import java.util.UUID;
public class UniqueIDTest {
public static void main(String[] args) {
UUID uniqueKey = UUID.randomUUID();
System.out.println (uniqueKey);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With