ThreadLocalRandom

A random number generator isolated to the current thread. Like the global {@link java.util.Random} generator used by the {@link java.lang.Math} class, a {@code ThreadLocalRandom} is initialized with an internally generated seed that may not otherwise be modified. When applicable, use of {@code ThreadLocalRandom} rather than shared {@code Random} objects in concurrent programs will typically encounter much less overhead and contention. Use of {@code ThreadLocalRandom} is particularly appropriate when multiple tasks (for example, each a {@link ForkJoinTask}) use random numbers in parallel in thread pools.

<p>Usages of this class should typically be of the form: {@code ThreadLocalRandom.current().nextX(...)} (where {@code X} is {@code Int}, {@code Long}, etc). When all usages are of this form, it is never possible to accidentally share a {@code ThreadLocalRandom} across multiple threads.

<p>This class also provides additional commonly used bounded random generation methods.

<p>Instances of {@code ThreadLocalRandom} are not cryptographically secure. Consider instead using {@link java.security.SecureRandom} in security-sensitive applications. Additionally, default-constructed instances do not use a cryptographically random seed unless the {@linkplain System#getProperty system property} {@code java.util.secureRandomSeed} is set to {@code true}.

@author Doug Lea

Members

Static functions

advanceProbe
int advanceProbe(int probe)

Pseudo-randomly advances and records the given probe value for the given thread.

getProbe
int getProbe()

Returns the probe value for the current thread without forcing initialization. Note that invoking ThreadLocalRandom.current() can be used to force initialization on zero return.

localInit
void localInit()

Initialize Thread fields for the current thread. Called only when Thread.threadLocalRandomProbe is zero, indicating that a thread local seed value needs to be generated. Note that even though the initialization is purely thread-local, we need to rely on (static) atomic generators to initialize the values.

nextSecondarySeed
int nextSecondarySeed()

Returns the pseudo-randomly initialized or updated secondary seed.

Static variables

seeder
long seeder;
Undocumented in source.
threadLocalRandomProbe
int threadLocalRandomProbe;

Probe hash value; nonzero if threadLocalRandomSeed initialized

threadLocalRandomSecondarySeed
int threadLocalRandomSecondarySeed;

Secondary seed isolated from public ThreadLocalRandom sequence

threadLocalRandomSeed
long threadLocalRandomSeed;

The current seed for a ThreadLocalRandom

Variables

BAD_BOUND
enum string BAD_BOUND;
Undocumented in source.
BAD_RANGE
enum string BAD_RANGE;
Undocumented in source.
BAD_SIZE
enum string BAD_SIZE;
Undocumented in source.

Meta