I need to generate a unique 10 digit ID in Java. These are the restrictions for this ID:
The best solution I found so far is the following:
private static int inc = 0;
private static long getId(){
long id = Long.parseLong(String.valueOf(System.currentTimeMillis())
.substring(1,10)
.concat(String.valueOf(inc)));
inc = (inc+1)%10;
return id;
}
This solution has the following problems:
Any other solution to create this ID?
Any other problem I haven't thought of with mine?
Thanks for your help,
use code new Random(System. currentTimeMillis()). nextInt(99999999); this will generate random ID up to 8 characters long.
A UUID is 36 characters long unique number. It is also known as a Globally Unique Identifier (GUID). A UUID is a class that represents an immutable Universally Unique Identifier (UUID). A UUID represents a 128-bit long value that is unique to all practical purpose.
This is a small enhancement to yours but should be resilient.
Essentially, we use the current time in milliseconds unless it hasn't ticked since the last id, in which case we just return last + 1
.
private static final long LIMIT = 10000000000L;
private static long last = 0;
public static long getID() {
// 10 digits.
long id = System.currentTimeMillis() % LIMIT;
if ( id <= last ) {
id = (last + 1) % LIMIT;
}
return last = id;
}
As it is it should manage up to 1000 per second with a comparatively short cycle rate. To extend the cycle rate (but shorten the resolution) you could use (System.currentTimeMillis() / 10) % 10000000000L
or (System.currentTimeMillis() / 100) % 10000000000L
.
This may be a crazy idea but its an idea :).
java.util.UUID.randomUUID().toString()
Second convert generated string to byte array (byte[]
)
Then convert it to long buffer: java.nio.ByteBuffer.wrap( byte
digest[] ).asLongBuffer().get()
Truncate to 10 digits
Not sure about uniqueness of that approach tho, I know that you can rely on uniqueness of UUIDs but haven't checked how unique are they converted and truncated to 10 digits long number.
Example was taken from JavaRanch, maybe there is more.
Edit: As you are limited to 10 digits maybe simple random generator would be enough for you, have a look into that quesion/answers on SO: Java: random long number in 0 <= x < n range
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With