Best way to generate a unique ID in java

非 Y 不嫁゛ 提交于 2019-12-20 02:28:07

问题


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 
{
   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 synchronisation overheads..

Is there any better approach please suggest?


回答1:


How about UUID: http://java.sun.com/j2se/1.5.0/docs/api/java/util/UUID.html#randomUUID%28%29




回答2:


UUID.randomUUID()



来源:https://stackoverflow.com/questions/2416211/best-way-to-generate-a-unique-id-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!