14

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
Silverstocking
  • 141
  • 1
  • 3

3 Answers3

20

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.

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
11

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.

skaffman
  • 398,947
  • 96
  • 818
  • 769
  • In terms of failure probability, I doubt the milliseconds approach would survive unit testing. – Dolph Feb 03 '11 at 00:25
  • @Dolph - or system load testing. Certainly it shouldn't ... if you are doing them properly. – Stephen C Feb 03 '11 at 00:57
  • 1
    I like UUID very much however it is quite inefficient (understood that the hard way...) the usual way to store is UUID.toString() which is awful 36bytes long (usually mapped to something like varchar(36)). DB indexes should be kept in memory - the bigger the index, the more memory needed, also indexing get slower, etc. I'd advise using some high-low scheme w/ clustering bits and `long` id. – bestsss Feb 25 '11 at 20:39
  • @bestsss: could you clarify a bit about the scheme with clustering bits that you proposed ? – Rajat Gupta Mar 06 '11 at 06:57
0

If your code ever runs in a clustered environment, it increases the odds that you have id collisions.

Most JPA databases have ways to generate unique ids by themselves.

http://en.wikibooks.org/wiki/Java_Persistence/Identity_and_Sequencing

MeBigFatGuy
  • 28,272
  • 7
  • 61
  • 66