views:

175

answers:

2

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  A: 

UUID.randomUUID()

Tim Drisdelle