Assuming that I am using the same seed by instantiating a static final Random object with new Random(), is it possible to get the same number twice by calling nextBytes in the same instance?
I am aware that for any given seed, all the possible “random” numbers can be determined, and it is really more like a sequence:
synchronized protected int next(int bits) {
seed = (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1);
return (int)(seed >>> (48 - bits));
}
So basically if I have this code:
private static final Random random = new Random();
public void doSomething() {
for (int i=0; i < 1000000000; i++) {
byte byteArray[] = new byte[8];
random.nextBytes(byteArray)
}
}
How likely is it that nextBytes will generate the same bytes before it goes thru all the possible numbers that it can generate?.
Would this return the same value before returning all the possible combinations for the given bits?. I am guessing yes, but how often would this happen?.
Class
Randomuses a linear congruence generator with a very large period. It does not repeate an int value for a very long time. The call tonextByteswith an 8-byte array generates two int values and breaks each into four 8-bit values to fill the array.I believe it is impossible for consecutive calls to
nextBytesto generate the same values. It would mean that the random number generator would have a period of 2. The docs specify a specific behavior fornextthat makes this impossible. (A subclass ofRandom, of course, can have any kind of pathological behavior you like, but an instance ofjava.util.Randomwill be well-behaved.)