Class SharedRandom

java.lang.Object
io.github.cjstehno.testthings.rando.SharedRandom
All Implemented Interfaces:
RandomGenerator

public class SharedRandom extends Object implements RandomGenerator
A thread-safe "random" number generated similar to the ThreadLocalRandom, but with the ability to have its seed changed after construction. The ability to know and change the seed at runtime is very useful in allowing for repeatable testing of "random"-based utilities. If you use the same seed, the same values will be generated in the same order. The seed may be injected programmatically, or a system property may be set ("test-tings.rando.seed") which will specify the seed for the whole JVM. NOTE: Setting the seed to a known value should ONLY be used for development and testing purposes.
  • Field Details

    • SEED_PROPERTY

      public static final String SEED_PROPERTY
      The System property which may be used to specify a custom seed value (e.g "test-things.rando.seed").
      See Also:
  • Method Details

    • current

      public static RandomGenerator current()
      Retrieves the singleton instance of the RandomGenerator for the current thread.
      Returns:
      the random generator instance
    • nextLong

      public long nextLong()
      Specified by:
      nextLong in interface RandomGenerator
    • reseed

      public void reseed(long newSeed)
      Updates the seed value and rebuilds the internal random generator.
      Parameters:
      newSeed - the new seed value
    • generator

      public static SharedRandom generator(Long seed)
      Builds a SharedRandom with the specified seed.
      Parameters:
      seed - the seed
      Returns:
      the SharedRandom instance
    • generator

      public static SharedRandom generator()
      Builds a SharedRandom with the default seed.
      Returns:
      the SharedRandom instance