开发者

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

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()

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜