在java中生成唯一ID的最佳方法

发布于 2024-08-24 08:57:57 字数 484 浏览 5 评论 0原文

在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文