Dynamically Creating New Generators

If you’re using a PRNG that implements the RandomGenerator.SplittableGenerator interface, then when a thread running in your application needs to fork a new thread, call the split() method. It creates a new generator with the same properties as the original generator. It does this by partitioning the original generator’s period into two; each partition is for the exclusive use of either the original or new generator.

The following example uses the L128X1024MixRandom PRNG, which implements the RandomGenerator.SplittableGenerator interface. The IntStream processes stream represents tasks intended to be run on different threads.

        int NUM_PROCESSES = 100;
        
        RandomGeneratorFactory<SplittableGenerator> factory =
            RandomGeneratorFactory.of("L128X1024MixRandom");
        SplittableGenerator random = factory.create();
       
        IntStream processes = IntStream.rangeClosed(1, NUM_PROCESSES);
        
        processes.parallel().forEach(p -> {
            RandomGenerator r = random.split();
            System.out.println(p + ": " + r.nextLong());
        });

Splittable PRNGs generally have large periods to ensure that new objects resulting from a split use different state cycles. But even if two instances "accidentally" use the same state cycle, they are highly likely to traverse different regions of that shared state cycle.