WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Java Concurrency · Expert · question 66 of 100

How does the Java ThreadLocalRandom class work and what are its benefits?

📕 Buy this interview preparation book: 100 Java Concurrency questions & answers — PDF + EPUB for $5

The ThreadLocalRandom class is a subclass of the Random class in Java that provides thread-local random number generation. It was introduced in Java 7 as part of the java.util.concurrent package and is designed to be used in multi-threaded applications. In this answer, we will discuss the working of ThreadLocalRandom class and its benefits.

How it works

The ThreadLocalRandom class uses a combination of thread-local storage and a shared pool of random number generators to provide thread-safe, high-performance random number generation. When a thread requests a random number from ThreadLocalRandom, it first checks if it has a local instance of the random number generator. If it does, it uses this generator to generate the random number. If it doesn’t have a local instance, it takes one from the shared pool and initializes it using a seed that is derived from a combination of the current system time and the thread ID.

The use of thread-local storage allows each thread to have its own random number generator, which reduces contention and improves performance. The shared pool of generators ensures that there are always enough generators available for all the threads, even when many threads are generating random numbers at the same time.

Here is an example that demonstrates the use of the ThreadLocalRandom class to generate random numbers in a multi-threaded environment:

import java.util.concurrent.ThreadLocalRandom;

public class RandomNumberGenerator implements Runnable {
    private int id;

    public RandomNumberGenerator(int id) {
        this.id = id;
    }

    public void run() {
        System.out.println("Thread " + id + " starting...");
        ThreadLocalRandom random = ThreadLocalRandom.current();
        for (int i = 0; i < 10; i++) {
            int number = random.nextInt(100);
            System.out.println("Thread " + id + ": " + number);
        }
        System.out.println("Thread " + id + " exiting...");
    }

    public static void main(String[] args) {
        Thread t1 = new Thread(new RandomNumberGenerator(1));
        Thread t2 = new Thread(new RandomNumberGenerator(2));
        Thread t3 = new Thread(new RandomNumberGenerator(3));
        t1.start();
        t2.start();
        t3.start();
    }
}

In this example, we create three threads that each generate ten random numbers using the ThreadLocalRandom class. We can see that each thread generates its own set of random numbers, and there is no interference between the threads.

Benefits

The benefits of using ThreadLocalRandom over a shared random number generator include:

Improved performance: By using thread-local storage and a shared pool of generators, ThreadLocalRandom avoids the contention that can occur when multiple threads access a shared random number generator. Improved scalability: As the number of threads in an application increases, the benefits of using ThreadLocalRandom become more pronounced. In contrast, a shared random number generator can become a bottleneck as the number of threads increases. Thread safety: ThreadLocalRandom is designed to be used in multi-threaded applications and provides thread-safe random number generation without the need for external synchronization.

Overall, the ThreadLocalRandom class is a useful tool for multi-threaded applications that require fast and efficient random number generation. It provides a simple and effective way to generate random numbers in a thread-safe and scalable manner.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Java Concurrency interview — then scores it.
📞 Practice Java Concurrency — free 15 min
📕 Buy this interview preparation book: 100 Java Concurrency questions & answers — PDF + EPUB for $5

All 100 Java Concurrency questions · All topics