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
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.
System. currentTimeMillis() returns a Java long . It will always be exactly 64 bits long and will typically have a number of leading zeroes.
currentTimeMillis() takes about 29 nanoseconds per call while System. nanoTime() takes about 25 nanoseconds.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With