Java Reference ยท Text, Formatting and Regex
The ThreadLocalRandom class
Reference for java.util.concurrent.ThreadLocalRandom: fast per-thread random numbers, bounded ranges, streams, and why you must not share or seed it.
java.util.concurrent.ThreadLocalRandom is a random number generator that belongs to the current thread. You do not create it; you ask for it with ThreadLocalRandom.current(). Because each thread has its own generator, there is no shared state and no contention, so it scales much better than one Random object used by many threads.
It supports range methods from the start (nextInt(origin, bound), nextDouble(origin, bound)) and implements RandomGenerator. You cannot set its seed, so its output is never reproducible.
int n = ThreadLocalRandom.current().nextInt(1, 7); // 1..6
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
public class ThreadLocalRandom extends Random public static ThreadLocalRandom current()
| Member | Description |
|---|---|
static ThreadLocalRandom current() |
The generator of the calling thread. |
nextInt(), nextInt(bound), nextInt(origin, bound) |
Random int, optionally bounded. |
nextLong(...), nextDouble(...), nextBoolean() |
Other primitive values. |
nextGaussian() |
Normal distribution. |
ints(...), longs(...), doubles(...) |
Streams of random numbers. |
Throws: UnsupportedOperationException from setSeed; IllegalArgumentException for an empty or inverted range.
Usage notes
- Always call
current()where you use it. Do not store the result in a field or pass it to another thread. The returned object is tied to the thread that calledcurrent(), and using it elsewhere shares state and breaks the guarantees. - Not reproducible. There is no seed, so it is unsuitable for tests that need the same numbers every run. Use a seeded
Randomthere. - Not secure. For tokens and keys use
SecureRandom. - Parallel streams:
ThreadLocalRandom.current()inside a parallel stream lambda is safe, because each worker thread calls it itself. - Virtual threads: works, but calling
current()inside the task, not outside, is still the rule. - Prefer it to
Math.random()in concurrent code;Math.random()shares one generator.
Related
Random,RandomGenerator,SecureRandom- Tutorial: Random numbers