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?
source
share