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
try
{
Thr开发者_JS百科ead.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 synchronisation overheads..
Is there any better approach please suggest?
How about UUID: http://java.sun.com/j2se/1.5.0/docs/api/java/util/UUID.html#randomUUID%28%29
UUID.randomUUID()
精彩评论