安全使用System.currentTimeMillis()生成唯一的数据库ID? [英] Safe to use System.currentTimeMillis() to generate a unique database ID?
问题描述
我在Java中使用 System.currentTimeMillis()
(返回 long
整数)来生成数据库实体的唯一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
推荐答案
不,这不安全。一个毫秒是CPU周期中的长时间(它们以每秒数十亿个周期运行,而不是数千个),因此如果一次有多个请求进入,或者多个线程都尝试创建数据库条目,它们将看到相同的CPU时间和将以碰撞键结束。如果系统时钟以某种方式重置或更改为较早时间,您也会遇到麻烦。
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.
这篇关于安全使用System.currentTimeMillis()生成唯一的数据库ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!