Best way to generate unique identifier in java

What is the best way to create a unique identifier in java. Usually people use

String id = System.currentTimeMillis+ someStaticCounter;

But this approach will require synchronization in multi-threaded applications.

I use

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

This approach helps me from synchronization overhead.

Is there a better approach please suggest?

+3
source share
2 answers

UUID.randomUUID ()

+1
source

Source: https://habr.com/ru/post/1736280/


All Articles