Hi,
I'm looking for the best way to create a unique ID as a String in Java.
Any guidance appreciated, thanks.
I should mention I'm using Java 5.
Hi,
I'm looking for the best way to create a unique ID as a String in Java.
Any guidance appreciated, thanks.
I should mention I'm using Java 5.
Try creating 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());
}
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());
}
}
}