## Why is this an issue?

Creating a new `Random` object each time a random value is needed is inefficient and may produce numbers that are not random, depending on the JDK. For better efficiency and randomness, create a single `Random`, store it, and reuse it.

The `Random()` constructor tries to set the seed with a distinct value every time. However, there is no guarantee that the seed will be randomly or uniformly distributed. Some JDK will use the current time as seed, making the generated numbers not random.

This rule finds cases where a new `Random` is created each time a method is invoked.

### Exceptions

This rule doesn’t apply to classes that use a `Random` in their constructors or the static `main` function and nowhere else.

## How to fix it

Define and reuse the `Random` object.

### Code examples

#### Noncompliant code example

    class MyClass {

        public void doSomethingCommon() {
          Random random = new Random();        // Noncompliant - new instance created with each invocation
          int rValue = random.nextInt();
        }
    }

#### Compliant solution

    class MyClass {
        private Random random = new Random();  // Compliant

        public void doSomethingCommon() {
          int rValue = this.random.nextInt();
        }
    }

## Resources

### Documentation

- Oracle Java SE - Random

### Articles & blog posts

- OWASP - Top 10 2017 Category A6 - Security Misconfiguration
- Baeldung - generating random number