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?
How about UUID class from the java.util package? It has the method that may suit your needs:
randomUUID()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