The ThreadLocalRandom Class – Concurrency: Part II
The ThreadLocalRandom Class
Some examples in this chapter make use of a pseudorandom generator. The class java.util.concurrent.ThreadLocalRandom provides a pseudorandom generator that is confined to the current thread—that is, it is local to the thread. The ThreadLocalRandom class extends the java.util.Random class, and provides methods that return uniformly distributed numerical values. The ThreadLocalRandom class is particularly recommended for concurrent tasks, instead of using a shared object of the Random class, as it entails less overhead and resource contention.
The code below illustrates use of the class in a task that simulates a dice. The current() static method of the class returns the ThreadLocalRandom object associated with the current thread.
int diceValue = ThreadLocalRandom.current().nextInt(1, 7); // [1, 6]
In addition, the ThreadLocalRandom class provides methods that return numerical streams whose elements are uniformly distributed pseudorandom numbers. The code below creates an int stream of 100 randomly generated int values which are in the interval [1, 6], and counts the number of times the dice value 6 occurs in the stream.
long count = ThreadLocalRandom.current()
.ints(100, 1, 7).filter(i -> i == 6).count();
Following selected methods are defined in the ThreadLocalRandom enum type:
static ThreadLocalRandom current()
Returns the ThreadLocalRandom object associated with the current thread.
int nextInt(int bound)
int nextInt(int origin, int bound)
The two methods return a pseudorandom, uniformly distributed int value between [0, bound) and [origin, bound), respectively, where [n, m) defines a half-open interval, where the end value is excluded.
The class ThreadLocalRandom also defines the analogous methods nextLong(), nextFloat(), and nextDouble() for the primitive types long, float, and double, respectively.
IntStream ints()
IntStream ints(long streamSize)
IntStream ints(int randomNumberOrigin, int randomNumberBound)
IntStream ints(long streamSize, int randomNumberOrigin,
int randomNumberBound)
Each method returns a stream of pseudorandom int values.
The first method returns an unlimited number of pseudorandom int values in the stream, which can be any legal int value.
The second method returns streamSize pseudorandom int values in the stream, which can be any legal int value.
The third method returns unlimited pseudorandom int values in the stream, which are in the half-open interval [randomNumberOrigin, randomNumberBound).
The fourth method returns streamSize pseudorandom int values in the stream, which are in the half-open interval [randomNumberOrigin, randomNumberBound).
The class ThreadLocalRandom also defines the analogous methods longs() and doubles() for the primitive types long and double that return LongStream and DoubleStream, respectively.