[英]Best way to generate a unique ID in java
在java中生成唯一ID的最佳方法是什么。 人們通常使用
String id = System.currentTimeMillis+ someStaticCounter;
但是這種方法需要在多線程應用程序中進行同步。
我在用
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();
這種方法可以幫助我避免同步開銷。
有什么更好的方法請建議嗎?
UUID.randomUUID()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.