Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Seeded RandomGenerators in Java 17

Java 17 has introduced a new RandomGeneratorFactory class for instantiating random number generators. The create(long) method is described as

Create an instance of RandomGenerator based on algorithm chosen providing a starting long seed. If long seed is not supported by an algorithm then the no argument form of create is used.

However there doesn't seem to be a method of RandomGeneratorFactory that can be used to determine if a long seed is supported. How is it possible to use the new API to obtain an instance of RandomGenerator that is guaranteed to be created using a supplied long seed?

like image 697
cpp beginner Avatar asked Feb 15 '26 09:02

cpp beginner


1 Answers

Probably, this is not the answer you want, but I became curious after reading your question and thought: Why not just probe the generator in question? Hence, I created a little scratch file with a heuristic approach:

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

import static java.util.stream.Collectors.toList;

class RandomGeneratorTool_73185029 {
  public static void main(String[] args) {
    RandomGeneratorFactory.all()
      .map(factory -> String.format("%-21s -> %sseedable", factory.name(), isSeedable(factory) ? "" : "not "))
      .forEach(System.out::println);
  }

  public static boolean isSeedable(RandomGeneratorFactory<RandomGenerator> factory) {
    final int ROUNDS = 3, NUMBERS_PER_ROUND = 100, SEED = 123;
    List<Integer>[] randomNumbers = new List[ROUNDS];
    for (int round = 0; round < ROUNDS; round++) {
      randomNumbers[round] = factory.create(SEED).ints(NUMBERS_PER_ROUND).boxed().collect(toList());
      if (round > 0 && !randomNumbers[round - 1].equals(randomNumbers[round]))
        return false;
    }
    return true;
  }
}

On JDK 21, this prints:

L32X64MixRandom       -> seedable
L128X128MixRandom     -> seedable
L64X128MixRandom      -> seedable
SecureRandom          -> not seedable
L128X1024MixRandom    -> seedable
L64X128StarStarRandom -> seedable
Xoshiro256PlusPlus    -> seedable
L64X256MixRandom      -> seedable
Random                -> seedable
Xoroshiro128PlusPlus  -> seedable
L128X256MixRandom     -> seedable
SplittableRandom      -> seedable
L64X1024MixRandom     -> seedable
like image 152
kriegaex Avatar answered Feb 17 '26 20:02

kriegaex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!