Java random number generator - creates a new random object for each random number * is functional * wrong?

Is there a chance that the next bit of code will ever print to the console?

while (true) {
    long t1 = System.nanoTime();
    long t2 = System.nanoTime();
    if (t1 == t2)
        System.out.println(t1 == t2);
}

What about:

Random r1 = new Random();
Random r2 = new Random();

with r1 and r2 having the same seed?

Another way to ask the same question is: is the next 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: Possible implementation of the new Random ():

public Random() {
    this(seedUniquifier() ^ System.nanoTime());
}

In fact, this is exactly the implementation of HotSpot.

+4
source share
1 answer

In javadoc System.nanoTime () it says:

This method provides nanosecond accuracy, but not necessarily nanosecond resolution (that is, how often the value changes) - no guarantees are provided, except that the resolution is no worse than currentTimeMillis ().

, , , .

: nanotime Random. javadoc :

. , , , .

, , , , , , .

, , . Javadoc of Random :

, : .

, javadoc.

+3

All Articles