Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 823
Silverstocking Avatar asked Feb 03 '11 00:02

Silverstocking


People also ask

What is System currentTimeMillis ()?

currentTimeMillis() method returns the current time in milliseconds. The unit of time of the return value is a millisecond, the granularity of the value depends on the underlying operating system and may be larger. For example, many operating systems measure time in units of tens of milliseconds.

How long is system currentTimeMillis?

System. currentTimeMillis() returns a Java long . It will always be exactly 64 bits long and will typically have a number of leading zeroes.

How fast is currentTimeMillis?

currentTimeMillis() takes about 29 nanoseconds per call while System. nanoTime() takes about 25 nanoseconds.


2 Answers

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.

like image 132
templatetypedef Avatar answered Oct 21 '22 05:10

templatetypedef


It's fairly unlikely you'll get a clash, yes (unless you're in a high-load system, in which case it's very likely), but still possible.

Java has an existing mechanism for generating unique identifiers, though - java.util.UUID. It has methods to generate random IDs.

I strongly suggest using that instead.

like image 34
skaffman Avatar answered Oct 21 '22 05:10

skaffman