java 生成长类型的 UUID

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4529727/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 06:46:49  来源:igfitidea点击:

generate UUID of long type

javauuiduniqueidentifier

提问by Mohamed Saligh

Please give me sample code to generate UUIDof longtype in java without using timestamp.

请给我示例代码生成UUIDlong,而无需使用时间戳Java类型。

Thanks

谢谢

回答by Stephen C

A real UUID is 128 bits. A long is 64 bits.

真正的 UUID 是 128 位。long 是 64 位。

This is not just pedantry. UUID stands for UniversalUnique IDentifier.

这不仅仅是迂腐。UUID 代表通用唯一标识符。

The "universal uniqueness" of the established UUID schemesare based on:

建立的 UUID 方案的“通用唯一性”基于:

  • encoding a MAC address and a timestamp,
  • encoding a hash of a DNS name and a timestamp, or
  • using a 122 bit random number ... which is large enough that the probability of a collision is very very small.
  • 对 MAC 地址和时间戳进行编码,
  • 编码 DNS 名称和时间戳的散列,或
  • 使用 122 位随机数......它足够大,碰撞的概率非常非常小。

With 64 bits, there are simply not enough bits for "universal uniqueness". For instance, the birthday paradox means that if we had a number of computers generating random 64 bit numbers, the probability of a potentially detectable collision would be large enough to be of concern.

对于 64 位,根本没有足够的位来实现“通用唯一性”。例如,生日悖论意味着,如果我们有许多计算机生成随机的 64 位数字,那么潜在可检测碰撞的概率将大到值得关注。

Now if you just want a UID (not a UUID), then any 64-bit sequence generator will do the job, provided that you take steps to guard against the sequence repeating. (If the sequence repeats, then the IDs are not unique in time; i.e. over time a given ID may denote different entities.)

现在,如果您只想要一个 UID(而不是 UUID),那么任何 64 位序列生成器都可以完成这项工作,前提是您采取措施防止序列重复。(如果序列重复,则 ID 在时间上不是唯一的;即随着时间的推移,给定的 ID 可能表示不同的实体。)

回答by Raghuram

Have you looked at java.util.UUID?

你看过java.util.UUID吗?

回答by Peter Lawrey

If you just want a simple unique long you can use AtomicLong.incrementAndGet(). This doesn't use a timestamp but does reset to 0 every time you start it and is not unique across JVMs.

如果你只想要一个简单的唯一 long 你可以使用 AtomicLong.incrementAndGet()。这不使用时间戳,但每次启动时都会重置为 0,并且在 JVM 中不是唯一的。

What is the requirement not to use timestamps all about? UUID uses a timestamp. (amoungst other things)

不使用时间戳的要求是什么?UUID 使用时间戳。(除其他外)