javauniqueidentifier

Best way to generate a unique ID in Java


What is the best way to generate a unique ID in Java. People generally use

String id = System.currentTimeMillis+ someStaticCounter;

But this approach would require synchronization in multithreaded applications.

I am using the following:

try {
    Thread.sleep(1); 
    // This sleep ensures that two consecutive calls from the same thread 
    // do not return the same ID.
} catch (InterruptedException e) {
    // do nothing;
}
id = System.currentTimeMillis() + "-" + Thread.currentThread().getId();

This approach helps me from synchronisation overheads.

Is there any better approach please suggest?


Solution

  • How about UUID class from the java.util package? It has the method that may suit your needs: