Class ThreadLocalRandomSource

java.lang.Object
org.apache.commons.rng.simple.ThreadLocalRandomSource

public final class ThreadLocalRandomSource
extends java.lang.Object
This class provides a thread-local UniformRandomProvider.

The UniformRandomProvider is created once-per-thread using the default construction method RandomSource.create(RandomSource).

Example:


 import org.apache.commons.rng.simple.RandomSource;
 import org.apache.commons.rng.simple.ThreadLocalRandomSource;
 import org.apache.commons.rng.sampling.distribution.PoissonSampler;

 // Access a thread-safe random number generator
 UniformRandomProvider rng = ThreadLocalRandomSource.current(RandomSource.SPLIT_MIX_64);

 // One-time Poisson sample
 double mean = 12.3;
 int counts = new PoissonSampler(rng, mean).sample();
 

Note if the RandomSource requires additional arguments then it is not supported. The same can be achieved using:


 import org.apache.commons.rng.simple.RandomSource;
 import org.apache.commons.rng.sampling.distribution.PoissonSampler;

 // Provide a thread-safe random number generator with data arguments
 private static ThreadLocal<UniformRandomProvider> rng =
     new ThreadLocal<UniformRandomProvider>() {
         @Override
         protected UniformRandomProvider initialValue() {
             return RandomSource.create(RandomSource.TWO_CMRES_SELECT, null, 3, 4);
         }
     };

 // One-time Poisson sample using a thread-safe random number generator
 double mean = 12.3;
 int counts = new PoissonSampler(rng.get(), mean).sample();
 
Since:
1.3
  • Method Summary

    Modifier and Type Method Description
    static UniformRandomProvider current​(RandomSource source)
    Returns the current thread's copy of the given source.

    Methods inherited from class java.lang.Object

    clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
  • Method Details

    • current

      public static UniformRandomProvider current​(RandomSource source)
      Returns the current thread's copy of the given source. If there is no value for the current thread, it is first initialized to the value returned by RandomSource.create(RandomSource).

      Note if the source requires additional arguments then it is not supported.

      Parameters:
      source - the source
      Returns:
      the current thread's value of the source.
      Throws:
      java.lang.IllegalArgumentException - if the source is null or the source requires arguments