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))


What is IS-A and HAS-A relationship in java : The pictorial(Diagram) way

What is IS-A and HAS-A relationship in java

To be frank since my childhood days I did't like to read and write much and so I always try to communicate things in pictorial way.

This is my first attempt with Java.

Below is the pictorial representation of IS-A and HAS-A relationship in java, I have tried my best to do justice with the topic, but all your suggestions will help me to improve my future posts.

IS-A and HAS-A relationship Example Diagram