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

强颜欢笑 提交于 2019-11-30 08:23:35

问题


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

回答1:


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.




回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/4881448/safe-to-use-system-currenttimemillis-to-generate-a-unique-database-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!