我需要生成唯一的编号为我的Java应用程序会在下面的需求 -
I need to generate unique numbers for my Java application meeting the below requirements -
9位十六进制 要生成约60万的数字日常 中的数字必须保持唯一的7天,最短期限;不是一个问题,如果他们重复超出为7天。 在高峰负荷,约800独特号码需要生成每秒约15秒钟。不成功的解决方案 -
Unsuccessful solution -
public static String getUniqueId() {
String uniqueTime = Long.toHexString(System.nanoTime());
String uniqueId = uniqueTime.substring(uniqueTime.length() - 9);
return uniqueId;
}
一个12位十六进制数字是通过使用nanoTime产生。我截断3左边的字符。 nanoTime帮助是处理峰值负载。
A 12 digit hexadecimal number is generated by using the nanoTime. I truncate the 3 left characters. nanoTime helps is handling the peak load.
我认为这是不正确的,它可能会导致重复。
I believe this is not correct and it may result in duplicates.
任何人都可以提供一个良好的快速算法吗?
Can anyone provide a good quick algorithm please?
如果只有一个线程用于生成的数字:
If only one thread is used to generate the numbers:
long nextId = counter % MAX_VALUE;
counter++;
return convertToHex(nextId);
如果多个线程:
long nextId = atomicLongCounter.getAndIncrement() % MAX_VALUE;
return convertToHex(nextId);
注:鉴于@甘博的计算,就需要313年达到最大值,所以你甚至可以丢弃模
Note: given @Gumbo's computation, it would need 313 years to reach the max value, so you can even drop the modulo.