Class ThreadLocalRandom

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

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

Instances of ThreadLocalRandom are not cryptographically
secure. Consider instead using SecureRandom
in security-sensitive applications. Additionally,
default-constructed instances do not use a cryptographically random
seed unless the system propertyjava.util.secureRandomSeed is set to true.

next

Generates the next pseudorandom number. Subclasses should
override this, as this is used by all other methods.

The general contract of next is that it returns an
int value and if the argument bits is between
1 and 32 (inclusive), then that many low-order
bits of the returned value will be (approximately) independently
chosen bit values, each of which is (approximately) equally
likely to be 0 or 1. The method next is
implemented by class Random by atomically updating the seed to

(seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1)

and returning

(int)(seed >>> (48 - bits)).

This is a linear congruential pseudorandom number generator, as
defined by D. H. Lehmer and described by Donald E. Knuth in
The Art of Computer Programming, Volume 3:
Seminumerical Algorithms, section 3.2.1.

nextGaussian

Returns the next pseudorandom, Gaussian ("normally") distributed
double value with mean 0.0 and standard
deviation 1.0 from this random number generator's sequence.

The general contract of nextGaussian is that one
double value, chosen from (approximately) the usual
normal distribution with mean 0.0 and standard deviation
1.0, is pseudorandomly generated and returned.

The method nextGaussian is implemented by class
Random as if by a threadsafe version of the following:

This uses the polar method of G. E. P. Box, M. E. Muller, and
G. Marsaglia, as described by Donald E. Knuth in The Art of
Computer Programming, Volume 3: Seminumerical Algorithms,
section 3.4.1, subsection C, algorithm P. Note that it generates two
independent values at the cost of only one call to StrictMath.log
and one call to StrictMath.sqrt.