Prefer ThreadLocalRandom over Random

Java 7 has introduced a new random number generator - ThreadLocalRandom

Normally to generate Random numbers, we either do
However in a concurrent applications usage of above leads to contention issues -
  • Random is thread safe for use by multiple threads. But if multiple threads use the same instance of Random, the same seed is shared by multiple threads. It leads to contention between multiple threads and so to performance degradation. 
ThreadLocalRandom is solution to above problem. ThreadLocalRandom has a Random instance per thread and safeguards against contention.

From the api docs - 
Usages of this class should typically be of the form: ThreadLocalRandom.current().nextX(...) (where X is IntLong, etc). When all usages are of this form, it is never possible to accidently share a ThreadLocalRandom across multiple threads.
Usage Example - 

//Generate a random number b/w 0 and 10.  0 <= R < 10
//Using Math.random()
int r1 = (int)Math.random()*10;
//Using Random
Random rand = new Random();
int r2 = rand.nextInt(10);
//Using ThreadLocalRandom
int r3 = ThreadLocalRandom.current().nextInt(10);


Update -
Reddit discussion on this post

Popular posts from this blog

Shortest Distance Graph Algorithms - How do they differ?

Java - One liner to Configure Logging