david david - 1 year ago 134
Java Question

How to create a 64 bit Unique Integer in Java?

I need to create a 64 bit Unique Integer in Java so that collision chances are pretty less.

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();

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();

Answer Source

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;

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)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download