Module java.base

Class RandomGeneratorFactory<T extends RandomGenerator>

java.lang.Object
java.util.random.RandomGeneratorFactory<T>
Type Parameters:
T - type of created random generator

public final class RandomGeneratorFactory<T extends RandomGenerator> extends Object
This is a factory class for generating multiple random number generators of a specific algorithm. RandomGeneratorFactory also provides methods for selecting random number generator algorithms. A specific RandomGeneratorFactory can be located by using the of(String) method, where the argument string is the name of the algorithm required. The method all() produces a non-empty Stream of all available RandomGeneratorFactorys that can be searched to locate a RandomGeneratorFactory suitable to the task. There are three methods for constructing a RandomGenerator instance, depending on the type of initial seed required. create(long) is used for long seed construction, create(byte[]) is used for byte[] seed construction, and create() is used for random seed construction. Example;
   RandomGeneratorFactory<RandomGenerator> factory = RandomGeneratorFactory.of("Random");

    for (int i = 0; i < 10; i++) {
        new Thread(() -> {
            RandomGenerator random = factory.create(100L);
            System.out.println(random.nextDouble());
        }).start();
    }
RandomGeneratorFactory also provides methods describing the attributes (or properties) of a generator and can be used to select random number generator algorithms. These methods are typically used in conjunction with all(). In this example, the code locates the RandomGeneratorFactory that produces RandomGenerators with the highest number of state bits.
    RandomGeneratorFactory<RandomGenerator> best = RandomGeneratorFactory.all()
        .filter(rgf -> !rgf.name().equals("SecureRandom")) // SecureRandom has MAX_VALUE stateBits.
        .sorted(Comparator.comparingInt(RandomGeneratorFactory<RandomGenerator>::stateBits).reversed())
        .findFirst()
        .orElse(RandomGeneratorFactory.of("Random"));
    System.out.println(best.name() + " in " + best.group() + " was selected");

    RandomGenerator rng = best.create();
    System.out.println(rng.nextLong());
Since:
17
See Also: