在java中生成唯一ID的最佳方法
在java中生成唯一ID的最佳方法是什么。 人们通常使用
String id = System.currentTimeMillis+ someStaticCounter;
但是这种方法需要在multithreading应用程序中进行同步。
我在用
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怎么样: http : //java.sun.com/j2se/1.5.0/docs/api/java/util/UUID.html#randomUUID%28%29
UUID.randomUUID()