Safe to use System.currentTimeMillis() to generate a unique database ID?

Silverstocking picture Silverstocking · Feb 3, 2011 · Viewed 7.6k times · Source

I'm using System.currentTimeMillis() (which returns a long integer) in Java to generate a unique ID for database entities since I assume that it's not possible for these times to overlap at any point.

Is this a safe assumption?

For example, at the moment I get this:

1296691225227

Answer

templatetypedef picture templatetypedef · Feb 3, 2011

No, this is not safe. A millisecond is a long time in CPU cycles (they run at billions of cycles per second, not thousands), so if multiple requests come in at a time or if multiple threads all try creating database entries they'll see the same CPU time and will end up with colliding keys. You'd also have trouble if the system clock somehow got reset or changed to an earlier time.