如何在 Java 中创建 64 位唯一整数 [英] How to create a 64 bit Unique Integer in Java

查看:58
本文介绍了如何在 Java 中创建 64 位唯一整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在 Java 中创建一个 64 位的唯一整数,以便降低冲突的机会.系统不是分布式的,所以不同计算机之间的冲突不是问题.

I need to create a 64 bit unique integer in Java so that collision chances are low. The system is not distributed, so collisions between different computers are not a problem.

有什么办法可以在 Java 中创建一个始终唯一的 64 位整数?

Is there any way, we can create a 64 bit integer in Java which is always Unique?

截至目前我正在使用 -

As of now I am using -

long number = System.nanoTime();

这是在 Java 中生成 64 位唯一整数的正确方法还是我可以尝试其他任何方法?

Is this the right way to generate 64 bit Unique Integer in Java or is there anything else I can try?

更新:-

这样做怎么样?这会是独一无二的吗?

How about doing this way? Will this be unique?

UUID number = UUID.randomUUID();
long uniqueNumber = number.timestamp();

推荐答案

如果您需要数字在一个进程中是唯一的,并且在重新启动之间保持稳健,您可以使用一个简单的 AtomicLong 和一个计时器.

If you need the numbers to be unique in one process, robust between restarts, you can use a simple AtomicLong and a timer.

private static final AtomicLong TS = new AtomicLong();
public static long getUniqueTimestamp() {
    long micros = System.currentTimeMillis() * 1000;
    for ( ; ; ) {
        long value = TS.get();
        if (micros <= value)
            micros = value + 1;
        if (TS.compareAndSet(value, micros))
            return micros;
    }
}

这将为您提供一个具有毫秒精度的独特时间戳",但每毫秒只能处理 1000 个 id,而不会超过实际时间.这在重新启动时效果很好,因为时间会超过以前的值(再次假设您平均每秒少于一百万)

This will give you a unique "timestamp" with a millisecond accuracy but can only handle 1000 ids per millisecond without getting ahead of the actual time. This works fine on restart as the time will jump past previous values (again assuming you have less than one million per second on average)

这篇关于如何在 Java 中创建 64 位唯一整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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