Mohd Farid
Mohd Farid

Reputation: 2070

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?

Upvotes: 4

Views: 3143

Answers (2)

Itay Maman
Itay Maman

Reputation: 30723

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

Upvotes: 9

Timothy
Timothy

Reputation: 2477

UUID.randomUUID()

Upvotes: 1

Related Questions