Monday, 5 March 2018

ThreadLocalRandom - Better way to generate random numbers

(Download One Minute Java Mobile app for latest Java updates 
App Link : One Minute Java )

Overview
Java 7 introduced ThreadLocalRandom and is a prat of java.util.concurrent package.
Main purpose of this class is to generate random numbers within given range.
Prior to Java 7 there were 2 methods of creating random numbers, one is by creating instance of java.util.Random or by using static random method of Math class i.e Math.random()

Limitation of old methods
In multi threaded environment where multiple threads use same instance of java.util.Random, same seed is shared by all threads. This lead to contention among threads and consequent poor performance.

Advantages of ThreadLocalRandom
ThreadLocalRandom is random number generator isolated to the current thread and the instance is not shared among other threads. This helps in avoiding contention problem as discussed before.
ThreadLocalRandom is 3 times faster than java.util.Random.
One important property of ThreadLocalRandom is we cannot set its seed explicitly, it is initialised with an internally generated seed, this helps it to mantain random sequence across threads.

Usage
Usages of this class should typically be of the form: ThreadLocalRandom.current().nextX(...) (where X is Int, Long, etc).
Above method helps to avoid accidental sharing of same instance among multiple threads

Example

  //Below statement will instantiate ThreadLocalRandom instane for current thread and will generate numbers between 0 to 100

 System.out.println(ThreadLocalRandom.current().nextInt(100))

 //This will generate number within a range of 50 to 100

 System.out.println(ThreadLocalRandom.current().nextInt(50,100))