Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Random Number Generator with Current Time vs Without

Tags:

java

random

I want to understand what the difference is between using a Random number generator with System.currentTimeMillis() as the seed and just using the default constructor. That is, what is the difference between this:

Random rand = new Random(System.currentTimeMillis());

and this:

Random rand = new Random();

I know that the numbers are pseudo-random, but I am yet to fully understand the details, and how they come about, between the level of 'randomness' one gets when current time is used as seed, and when the default constructor is used.

like image 468
ayePete Avatar asked Aug 28 '15 17:08

ayePete


2 Answers

If you want your random sequences to be the same between runs you can specify a seed. Usually you don't want that to happen so you use a different seed for every run and System.currentTimeMillis() is reasonable seed commonly used.

If you are writing a multithreaded program where multiple threads will initialize the Random object at the same time, then you may want to avoid using System.currentTimeMillis() and instead let Java use its own initialization.

like image 176
Josep Valls Avatar answered Oct 13 '22 20:10

Josep Valls


Supplying your own seed is useful for simulations where you purposely want to generate the same sequence of pseudorandom values multiple times. In general, though, it's just as well to use the default constructor.

When the default constructor is used, the docs say:

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.

In other words, it generates its own seed internally. The details depend on the particular Java implementation being used. One implementation I've seen has this:

private static volatile long seedBase = 0;

public Random() {
    setSeed(System.nanoTime() + seedBase);
    ++seedBase;
}

The actual quality of the randomness doesn't change. If the quality of the random sequence is of concern to you, you can also use java.security.SecureRandom, which has better cryptographic behavior. (See, e.g., this thread.)

like image 22
Ted Hopp Avatar answered Oct 13 '22 21:10

Ted Hopp