开发者

Best way to generate a unique ID in java

开发者 https://www.devze.com 2022-12-22 17:05 出处:网络
What is the best way to generate a unique ID in java. People generally use String id = System.currentTimeMillis+ someStaticCounter;

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

精彩评论

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