For my current java project, I am trying to generate random ID's
for registered users. So far I have been using min +(int) (Math.random()*((max-min)+1))
as my formula to generate the random number. The problem that I am facing is that sometimes the numbers repeat themselves and my application wouldn't work with them.
int min = 1001;
int max = 1050;
for (int i=1; i<=1; i++)
{
int a = min +(int) (Math.random()*((max-min)+1));
}
I have tried using and incorporating
Integer[] arr = new Integer[100];
for (int i = 1; i < arr.length; i++) {
arr[i] = i;
}
Collections.shuffle(Arrays.asList(arr));
but numbers generated would constantly come out as "null" and it would repeat the loop a few hundred times and flood my txt file.
In general, random generators Random
or Math.random()
are not the correct ways to generate a unique id. As you mentioned, it could be repeated (and it will definitely be).
I would recommend two ways of generating ID
.
The first one is to use AtomicInteger
. This is good when your ID
should be unique but not random .
private static final AtomicInteger ID = new AtomicInteger(0);
public static String generateUniqueId() {
return String.valueOf(ID.incrementAndGet());
}
The second one, which is preferable to me, is to use UUID
. This is good when your ID
should be as unique as random .
public static String generateUniqueId() {
return String.valueOf(UUID.randomUUID());
}
Another one, I can mention is to use System.nanoTime()
.
public static String generateUniqueId() {
return String.valueOf(System.nanoTime());
}
Long ago I had some investigation and find out that this is pretty stable for normal payload. But in general, it could retrieve the same value if you build such a system, that should generate ID
so often.
Instead of generating numbers I would recommend to generate UUID. The chance of a is collision is much smaller.
UUID id = UUID.randomUUID();
Otherwise if you want to stick with numbers I would recommend you to implement yourself some Sequence service within your application.
import java.util.concurrent.atomic.AtomicLong;
public class SequenceService {
private final AtomicLong ids;
public SequenceService() {
long initialValue = getInitialValue();
this.ids = new AtomicLong(initialValue);
}
public long generateNextId() {
return ids.incrementAndGet();
}
private long getInitialValue() {
// this methods reads the last known leased id (e.g. from the file system)
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.