Video in progress
Why use ThreadLocalRandom instead of Random in multithreaded code?
java.util.Random is thread-safe, but on every call it updates its internal seed with CAS on a single AtomicLong, and with many threads that spot becomes a bottleneck. ThreadLocalRandom keeps separate state per thread, so there is no contention.
📖 Answer
It's common to see code where all threads use one shared Random:
private static final Random RND = new Random();
long backoff(int attempt) {
return (1L << attempt) * 100 + RND.nextInt(100); // jitter
}
The result is correct, but inside nextInt the seed is updated with a compareAndSet loop. When 64 threads call it at once, they fight over one cache line and CAS retries pile up.
long backoff(int attempt) {
return (1L << attempt) * 100 + ThreadLocalRandom.current().nextInt(100);
}
ThreadLocalRandom.current() doesn't create a new object: the seed lives in a field on the Thread object itself. So don't store it in a field or hand it to another thread. Call current() at the point of use every time. Otherwise threads can end up with the same sequence of numbers.
When you need something else:
- tokens, passwords, session IDs: only
SecureRandom.ThreadLocalRandomis not cryptographic; - if you need a reproducible sequence in a test: a
Randomcreated with a seed, or theRandomGeneratorfamily from Java 17 (SplittableRandom,RandomGenerator.of("L64X128MixRandom")).
Since Java 17, ThreadLocalRandom also implements the RandomGenerator interface, so the API is the same and switching is easy.
Sign up to mark studied questions and save your progress.