Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
320 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...