00:00

Enhanced Pseudo-Random Number Generators in Java 17

Last updated: · Standard (Java 17)

Java 17 (JEP 356) introduced the java.util.random package with a common RandomGenerator interface, new families of algorithms such as LXM, and RandomGeneratorFactory for choosing an algorithm by name.

This tutorial shows how to write code against the interface, compare algorithms, and create independent generators for parallel work.

1. Why Was a New Random API Needed?

Java already had Random, SecureRandom, ThreadLocalRandom and SplittableRandom, but they shared no common interface. Switching algorithms meant changing code, and missing features had to be added to each class separately. The new API gives them one type, adds modern algorithms with better statistical quality, and makes the algorithm a configuration choice.

2. Key Types

TypePurpose
RandomGeneratorcommon interface; nextInt(origin, bound), ints(), nextDouble(), ...
RandomGeneratorFactoryfinds algorithms by name and creates seeded or unseeded instances
SplittableGeneratorcan split into independent child generators for parallel tasks
JumpableGenerator, LeapableGeneratorcan jump far ahead in their sequence
Syntax.java
RandomGenerator rng = RandomGenerator.of("L64X128MixRandom");
RandomGenerator seeded = RandomGeneratorFactory.of("L32X64MixRandom").create(42);
RandomGenerator legacy = new java.util.Random();   // also a RandomGenerator now

3. Practical Examples

Example 1: Swapping algorithms behind one interface

The simulation method accepts any RandomGenerator. Each algorithm is seeded with the same value, so the output is repeatable.

AlgorithmChoice.java
import java.util.random.RandomGenerator;
import java.util.random.RandomGeneratorFactory;

public class AlgorithmChoice {
    // Simulation code depends only on the interface
    static double averageRoll(RandomGenerator rng, int rolls) {
        return rng.ints(rolls, 1, 7).average().orElse(0);
    }

    public static void main(String[] args) {
        String[] names = { "Random", "L32X64MixRandom", "Xoroshiro128PlusPlus" };
        for (String name : names) {
            RandomGenerator rng = RandomGeneratorFactory.of(name).create(17);   // seeded: repeatable
            System.out.printf("%-22s average of 10000 rolls = %.3f%n", name, averageRoll(rng, 10_000));
        }

        // Every generator now has bounded methods with an origin
        RandomGenerator rng = RandomGenerator.of("L64X128MixRandom");
        int pin = rng.nextInt(1000, 10000);
        System.out.println("4-digit PIN in range: " + (pin >= 1000 && pin < 10000));
    }
}
Output
Random                 average of 10000 rolls = 3.516
L32X64MixRandom        average of 10000 rolls = 3.494
Xoroshiro128PlusPlus   average of 10000 rolls = 3.491
4-digit PIN in range: true

Example 2: Inspecting algorithms and splitting

FactoryProperties.java
import java.util.Comparator;
import java.util.random.RandomGenerator;
import java.util.random.RandomGeneratorFactory;

public class FactoryProperties {
    public static void main(String[] args) {
        // Inspect the algorithms that support splitting for parallel work
        RandomGeneratorFactory.all()
                .filter(RandomGeneratorFactory::isSplittable)
                .sorted(Comparator.comparing(RandomGeneratorFactory::name))
                .limit(4)
                .forEach(f -> System.out.println(f.name() + " | state bits " + f.stateBits()
                        + " | period about 2^" + f.period().bitLength()));

        // A splittable generator creates independent children for parallel tasks
        RandomGenerator.SplittableGenerator root =
                RandomGenerator.SplittableGenerator.of("L64X128MixRandom");
        long distinct = root.splits(4).mapToLong(RandomGenerator::nextLong).distinct().count();
        System.out.println("Independent child generators: " + distinct);
    }
}
Output
L128X1024MixRandom | state bits 1152 | period about 2^1152
L128X128MixRandom | state bits 256 | period about 2^256
L128X256MixRandom | state bits 384 | period about 2^384
L32X64MixRandom | state bits 96 | period about 2^96
Independent child generators: 4

The LXM family combines a linear congruential generator with an xorshift generator, which gives long periods and good statistical quality.

4. How the API Is Organised

From algorithm name to random numbers An algorithm name is looked up by RandomGeneratorFactory, which creates a RandomGenerator, optionally seeded, that produces numbers or streams. Algorithm name "L64X128MixRandom" RandomGeneratorFactory of(name) create(seed) RandomGenerator nextInt / ints() random values
Figure 1: The algorithm becomes a string you can change without touching the code that uses it.

5. Important Points and Best Practices

  • Program against RandomGenerator, not a concrete class.
  • RandomGenerator.getDefault() returns a good general-purpose algorithm (currently L32X64MixRandom).
  • For security tokens and passwords, still use SecureRandom; the LXM generators are not cryptographically secure.
  • Use seeds only for repeatable tests and simulations.
  • Use splits() for parallel streams instead of sharing one generator between threads.

6. Summary

  • Java 17 added java.util.random (JEP 356).
  • RandomGenerator is the common interface for old and new algorithms.
  • RandomGeneratorFactory selects algorithms by name.
  • Splittable and jumpable generators support parallel workloads.

Related Tutorials

7. References