patternjavaModerate
Generating a 64 bit unique integer in Java
Viewed 0 times
uniquebitjavageneratinginteger
Problem
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:
I will be running the above code in production.
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.
Solution
My specification is only to generate the 64 bit unique integer, that's it.
In this case, there's no need for anything more complicated than atomically incrementing a counter:
To offer a more specific critique of your code, it's unnecessarily complicated and inefficient. I don't see anything incorrect about it (i.e. it seems like it meets your criteria), but there's the old saying about obviously no bugs vs no obvious bugs (paraphrased).
In this case, there's no need for anything more complicated than atomically incrementing a counter:
public class Counter {
private static final AtomicLong counter = new AtomicLong(0);
public static long getNextNumber(){
return counter.incrementAndGet();
}
}To offer a more specific critique of your code, it's unnecessarily complicated and inefficient. I don't see anything incorrect about it (i.e. it seems like it meets your criteria), but there's the old saying about obviously no bugs vs no obvious bugs (paraphrased).
Code Snippets
public class Counter {
private static final AtomicLong counter = new AtomicLong(0);
public static long getNextNumber(){
return counter.incrementAndGet();
}
}Context
StackExchange Code Review Q#79818, answer score: 12
Revisions (0)
No revisions yet.