ThreadLocalRandom

Guide to using ThreadLocalRandom with examples.

If you are interviewing, consider buying our number#1 course for Java Multithreading Interviews.

Overview

The class java.util.concurrent.ThreadLocalRandom is derived from java.util.Random and generates random numbers much more efficiently than java.util.Random in multithreaded scenarios. Interestingly, Random is thread-safe and can be used by multiple threads without malfunction, just not efficiently.

To understand why an instance of the Random class experiences overhead and contention in concurrent programs, we’ll delve into the code for one of the most commonly used methods nextInt() of the Random class. The code is reproduced verbatim from the Java source code below:

    /**
     * Generates the next pseudorandom number. Subclasses should
     * override this, as this is used by all other methods.
     *
     * <p>The general contract of {@code next} is that it returns an
     * {@code int} value and if the argument {@code bits} is between
     * {@code 1} and {@code 32} (inclusive), then that
...