1

I have method that creates elasticsearch documents. It uses OpenStreetMap Object IDs as the ES document ID. I now also want to add other documents that do not have an OSM id.

I cannot use a UUID generator since the method requires a long.

What is the best way to get a "pseudo" UUID with a long type?

Chris
  • 13,100
  • 23
  • 79
  • 162
  • 1
    Possible duplicate of [How to generate unique Long using UUID](http://stackoverflow.com/questions/15184820/how-to-generate-unique-long-using-uuid) – vk239 Feb 16 '16 at 22:05

2 Answers2

3

You can achieve a long UID generating a random sequence of 64bit, i.e. using AtomicLong().

AtomicLong is a long value that may be updated atomically. An AtomicLong is used in applications such as atomically incremented sequence numbers

private static final AtomicLong TS = new AtomicLong();
public static long getUniqueTimestamp() {
    return TS.incrementAndGet();
}

Each call of getUniqueTimestamp() returns a unique id for the process, starting from 0.

You can start from an higher value initializing Atomic with current time:

private static final AtomicLong TS = new AtomicLong(System.currentTimeMillis() * 1000);

Note

this is not an UNIVERSAL UID, just a UID!

jenjis
  • 1,077
  • 4
  • 18
  • 30
0

How about the following:

import org.apache.commons.lang3.RandomStringUtils;

public class RandomLong {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        long id = Long.parseLong(RandomStringUtils.randomNumeric(18));
        System.out.println("id = " + id);
    }

}

It ensures positive longs, which is ideal for IDs.

Here is another answer that puts more emphasis on uniqueness by using nano time and an atomic counter.

import java.util.concurrent.atomic.AtomicInteger;

public class UniqueLong {


    static AtomicInteger atom = new AtomicInteger(0);

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        long id = Long.parseLong(System.nanoTime() + "" + (atom.getAndIncrement() % 1_000));
        System.out.println("id = " + id);
    }

}
Jose Martinez
  • 11,452
  • 7
  • 53
  • 68