Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 522
Mohd Farid Avatar asked Nov 07 '25 21:11

Mohd Farid


1 Answers

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

  • randomUUID()
like image 173
Itay Maman Avatar answered Nov 10 '25 10:11

Itay Maman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!