Random over ThreadLocalRandom

This might help a little:

http://thoughtfuljava.blogspot.com/2012/09/prefer-threadlocalrandom-over-random.html


Quoted from source:

Normally to generate random numbers, we either do create an instance of java.util.Random or Math.random() – which internally creates an instance of java.util.Random on first invocation. 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.


So, basically, using a random instance per thread allows you to stop synchronizing on the seed which must be used by all threads.

Leave a Comment