Java

Java

Made by DeepSource

Random instances should be reused JAVA-W1015

Anti-pattern
Major
cwe-337

Creating a new instance of java.util.Random every time a random value is required is wasteful. In addition, the randomness of the values produced is reduced due to increased predictability of the random number generation.

Store a single Random instance and reuse it for best effect.

As per the JavaDocs for java.util.Random:

If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers.

Because the final stream of random numbers generated by Random is only dependant on the initial seed value, it is a bad idea to create Random instances with constant seed values.

It is also not recommended to create new instances every time a random number is required. A number of JDKs implement Random by using the system clock to initialize the seed when it is not provided. When a new instance is created each time, the reliance of the seed generation algorithm on the system clock reduces the quality of the resulting random number distribution.

Bad Practice

Random instances must not be discarded after only a single use.

int someInt = new Random().nextInt();

someInt = new Random().nextInt();

Recommended

Random rng = new Random(); // Maybe this is an instance field.

// ...

int someInt = rng.nextInt();

// ...

boolean someBool = rng.nextBoolean();

Another option is to use Math.random(), which is a readily available static method that returns a random double value in the range0.0 <= x < 1.0.

int someInt = (int)(Math.random() * 100) % 10; // gets a random number in the range 0-10

Note: While the Oracle and OpenJDK implementations of Random are thread-safe, it is not recommended to rely on this fact. Consider using Math.random(), or create a Random instance for each thread if you need RNG across multiple threads. Keeping per-thread instances will avoid the performance penalty of synchronization that Math.random() could suffer from.

References