Is there any chance of the following bit of code ever printing something to the console?
while (true) {
long t1 = System.nanoTime();
long t2 = System.nanoTime();
if (t1 == t2)
System.out.println(t1 == t2);
}
And what about:
Random r1 = new Random();
Random r2 = new Random();
having r1 and r2 having the same seed?
Other way of asking the same question is: is the following bit of code correct?
// generate k random integers
int[] random_numbers = new int[k];
for (int i = 0; i < k; ++i) {
Random r = new Random();
random_numbers[i] = r.nextInt();
}
EDIT: A possible implementation of new Random() is:
public Random() {
this(seedUniquifier() ^ System.nanoTime());
}
In fact, that's exactly HotSpot's implementation.
The javadoc of System.nanoTime() says:
This method provides nanosecond precision, but not necessarily nanosecond resolution (that is, how frequently the value changes) - no guarantees are made except that the resolution is at least as good as that of currentTimeMillis().
So yes, there is a chance that two consecutive calls produce the same value.
That is unrelated to the second part though: the nanotime is not used to seed a new Random. The Random constructor javadoc says:
Creates a new random number generator. This constructor sets the seed of the random number generator to a value very likely to be distinct from any other invocation of this constructor.
So, it's very unlikely for two Random created consecutively to have the same seed, and thus to produce the same random number.
That doesn't mean it's a good idea to recreate a Random every time you need one. The javadoc of Random says:
An instance of this class is used to generate a stream of pseudorandom numbers
So you can just reuse the same instance: it will be faster, and will produce a stream of random numbers.
All your questions can thus be answered by simply reading the javadoc.
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