在java中生成唯一ID的最佳方法
在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();
这种方法可以帮助我减轻同步开销。
请问有更好的方法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
UUID 怎么样:
http://java .sun.com/j2se/1.5.0/docs/api/java/util/UUID.html#randomUUID%28%29
How about UUID:
http://java.sun.com/j2se/1.5.0/docs/api/java/util/UUID.html#randomUUID%28%29
UUID.randomUUID()
UUID.randomUUID()