唯一编号生成算法 [英] Unique Number Generation Algorithm

查看:205
本文介绍了唯一编号生成算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要生成唯一的编号为我的Java应用程序会在下面的需求 -

I need to generate unique numbers for my Java application meeting the below requirements -

  1. 9位十六进制
  2. 要生成约60万的数字日常
  3. 中的数字必须保持唯一的7天,最短期限;不是一个问题,如果他们重复超出为7天。
  4. 在高峰负荷,约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.

这篇关于唯一编号生成算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆