Randam vs ThreadLocalRandom vs SecureRandom Example in Java

Hello guys, one of the common tasks for Java developers is to generate an array of random numbers, particularly in game development. For example, if you are coding for dice-based games like Ludo or Snake and Lader then you need to generate a random number from 1 to 6 to simulate dice behavior. The same goes for other dice-based games. There are many cases where you need to generate random numbers and an array of random numbers. In some cases, duplicates may be allowed while other duplicates are not permitted.  


In this program for simplicity, your array may contain duplicates. In Java, there are many classes and utilities to generate random numbers like java.util.Random, SecureRandom, and ThreadLocalRandom which we'll see in this article.

If you are thinking about how to generate random numbers in the array then you don't need to take stress just create an array and filled with random numbers, as shown in the example. You can also use this example to generate 100 random numbers in Java as well to generate random numbers between 0 and 1 or any numbers.

Actually, it's rather easy to generate a random number between 0 and 1 by using the Math.random() method which is available since JDK 1.0. This method returns a double value which is always between 0 and 1, precisely greater than 0.0 and less than 1.0

Another common way of generating random numbers in Java is by using java.util.Random class and its nextInt() method. The nextInt() is overloaded method in java.util.Random class and one versions nextInt() without argument returns a random integer value in the range of Integer.MIN_VALUE to Integer.MAX_VALUE, while another one nextInt(int range) returns a random integer from 0 to supplied value.  You can further join The Complete Java MasterClass to learn more about the modern style of coding in Java.




1. SecureRandom 

This is a relatively newer class provides a cryptographically strong random number generator (RNG). The randomness depends upon seed that's why any seed material passed to a SecureRandom object must be unpredictable, and all SecureRandom output sequences must be cryptographically strong.

Here is how you can create an instance of SecureRandom in Java:

SecureRandom random = new SecureRandom();

You can also use the following methods to retrieve random bytes:

     SecureRandom random = new SecureRandom();
      byte bytes[] = new byte[20];
      random.nextBytes(bytes);

You can also use the generateSeed() method to generate a given number of seed bytes :

  byte seed[] = random.generateSeed(20);

An important thing to remember is that depending on the implementation, the generateSeed() and nextBytes() methods may block as entropy is being gathered, for example, if they need to read from /dev/random on various Unix-like operating systems.



Randam vs ThreadLocalRandom vs SecureRandom Example in Java






2. ThreadLocalRandom

This is another random number generator that was added on Java 7. This random number generator isolated to the current thread. Like the global Random generator used by the Math class, a ThreadLocalRandom is initialized with an internally generated seed that may not otherwise be modified.

Using ThreadLocalRandom in concurrent programs will typically encounter much less overhead and contention than using the global Random class. You can use ThreadLocalRandom when multiple tasks like a ForkJoinTask need random numbers in parallel in thread pools.


3. Java Program to Generate Random Numbers

Here is our complete working Java program to generate Random numbers. If you want to try this code snippet, you can create a Java project in your Eclipse IDE, then select the code here and paste it into your Java Project. The eclipse will automatically create the correct package and source file to accommodate an example. After that, you just simply execute

import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

/**
 * Java Program to demonstrate how to generate random numbers.
 * In this program, we will learn
 * how to generate an array of random numbers
 * 100 random numbers for general use
 * securely generated random integers using SecureRandom
 * how to use ThreadLocalRandom in Java
 * generating random between 0 and 1
 * how to generate random number in a range
 *
 * @author WINDOWS 8
 *
 */
class RandomNumberDemo {

    public static void main(String args[]) {

        // how to generate random numbers in array Java      
        int[] randoms = new int[10];
        for(int i =0; i<randoms.length; i++){
            randoms[i] = (int) (Math.random()*100);
        }
        System.out.println("Array of random numbers in Java : " 
                             + Arrays.toString(randoms));
       

        // how to generate 100 random numbers in java
        int[] numbers = new int[100];
        Random rand = new Random();
        for(int i =0; i<numbers.length; i++){
            numbers[i] = rand.nextInt(100);
        }
        System.out.println("100 random numbers : " + Arrays.toString(numbers));

        // Random long generator in Java
        long longRandom = rand.nextLong();
        System.out.println("Random long number : " + longRandom);

        // Java random number between 0 and 1
        int random = (int) (Math.random()*100);
        System.out.println("Random number between 0 and 1 : " + random);

       
        // SecureRandom to securely generate random number in Java
        // Can be slow if not enough seeds are generated
        Random secure = new SecureRandom();
        int secureRandomNumber = secure.nextInt(100);
        System.out.println("Securely generated random number in Java : " 
                                 + secureRandomNumber);
       
        // ThreadLocalRandom to efficient generate random numbers
        // Each thread has it's own ThreadLocalRandom
        // You should always use it as shown below to take it's full advantage
        int tillTwenty = ThreadLocalRandom.current().nextInt(20);
        System.out.println("Random numbers generation using ThreadLocalRandom : "
                                               + tillTwenty);

    }

}


Output
Array of random numbers in Java : [78, 19, 39, 5, 10, 54, 48, 95, 78, 7]
100 random numbers : [87, 15, 36, 86, 12, 20, 14, 29, 10, 12, 25, 60, 50,
 77, 38, 84, 87, 12, 11, 10, 86, 13, 80, 29, 21, 83, 83, 60, 66, 43, 40,
 77, 69, 75, 77, 69, 81, 16, 36, 99, 27, 37, 94, 92, 4, 91, 46, 77, 99,
 1, 35, 42, 51, 25, 34, 92, 75, 2, 22, 41, 44, 73, 90, 91, 71, 39, 81,
 26, 28, 33, 62, 31, 55, 83, 30, 35, 19, 7, 92, 14, 52, 77, 51, 53, 38,
 80, 3, 26, 28, 68, 9, 75, 67, 64, 1, 91, 21, 92, 23, 40]
Random long number : -7015844924955679434
Random number between 0 and 1 : 71
Securely generated random number in Java : 5
Random numbers generation using ThreadLocalRandom : 2


That's all about different ways to generate an array of random numbers in Java. In this program, we have seen how you can use Random, SecureRandom, and ThreadLocalRandom classes to create random numbers in Java. You can also use the Math.random() method if you want an easy solution. ThreadLocalRandom provides an efficient way to generate random numbers in a multi-threaded program becuase random number generated is not shared.

Other Java programming and OOP tutorials You may like

Thanks for reading this article so far. If you like this core Java tutorial then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.

P. S. - If you are serious about learning core Java and looking for a free online course to start with then you can also check this list of free core Java for beginners. It's completely free and you just need a free Udemy account to join this course.

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.