Skip to content
Tutorials Center
My learning

Topics

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.

Java
int n = ThreadLocalRandom.current().nextInt(1, 7); // 1..6

Try it

Java Ranges from the current thread

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.

Java Using it from several threads

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

Java
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 called current(), 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 Random there.
  • 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.