I need to generate a 64 bit unique integer in Java. I need to make sure that there is very few or no collisions if possible.
I came up with the below code which works fine:
public class TestUniqueness {
private static final AtomicLong TS = new AtomicLong();
public static void main(String[] args) {
// for testing, just added the for loop
for (int i = 1; i <= 100000; i++) {
System.out.println(getUniqueTimestamp());
}
}
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;
}
}
}
I will be running the above code in production.
random
but you are just getting the current time without repeats, which doesn't qualify as random in my book. \$\endgroup\$System.nanoTime()
(Don't see relation to tag random) \$\endgroup\$