Generating concurrent random numbers

The Java concurrency API provides a specific class to generate pseudorandom numbers in concurrent applications. It's the ThreadLocalRandom class and it's new in Java 7 version. It works as the thread's local variables. Every thread that wants to generate random numbers has a different generator, but all of them are managed from the same class, in a transparent way to the programmer. With this mechanism, you will get a better performance than using a shared Random object to generate the random numbers of all the threads.

In this recipe, you will learn how to use the ThreadLocalRandom class to generate random numbers in a concurrent application.

Get Java 9 Concurrency Cookbook - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.