Skip to content
Related Articles

Related Articles

Improve Article

ThreadLocalRandom vs SecureRandom Class in Java

  • Last Updated : 26 May, 2021

The ThreadLocalRandom class of java.util package is a random number generator that generates random numbers isolated to the current thread. It is a subclass of the Random class. It is initialized with an internally generated seed value that cannot be modified. 

ThreadLocalRandom would be useful in applications where several threads are running concurrently, since the random number generation remains isolated the threads don’t have to compete for shared instances (like in the case of Random class instances) and gives better performance and lower overhead. However, it is not cryptographically secure. This is where SecureRandom comes into play which is discussed later in this post.

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

Syntax:

public class ThreadLocalRandom extends Random

The usage of ThreadLocalRandom is generally of the form:



ThreadLocalRandom.current().nextX(...) {where X = Int, Long, Double etc}

Implementation:

Suppose two threads are created in the main() method. Now inside the run() method we call the ThreadLocalRandom.current.nextInt(). The run() method of the Thread class is where the executable part of any thread is written. When the thread is started using the start() method, run() is called intrinsically. The Threads run and generate random integer values as we call the nextInt() method of ThreadLocalRandom.

They may generate the same number with the same seed value but the generation is still isolated i.e. there is no competition for space, like in the case of shared objects.

Example:

Java




// java Program to illustrate ThreadLocalRandom class
  
// Importing class from java.util.concurrent package
import java.util.concurrent.ThreadLocalRandom;
  
// Main class
public class ThreadLocalRandomNumbers extends Thread {
  
    // The run() method of the Thread class
    // Must be defined by every class that extends it
    public void run()
    {
  
        // Try method to check for exceptions
        try {
            // Call the ThreadLocalRandom
            int r = ThreadLocalRandom.current().nextInt(20);
  
            // Print the generated number r
            System.out.println(
                "Thread " + Thread.currentThread().getId()
                + " generated " + r);
        }
  
        // Catch block to handle the exceptions
        catch (Exception e) {
            System.out.println("Exception");
        }
    }
    public static void main(String[] args)
    {
        // Create 2 threads
        ThreadLocalRandomNumbers t1
            = new ThreadLocalRandomNumbers();
        ThreadLocalRandomNumbers t2
            = new ThreadLocalRandomNumbers();
  
        // Start the threads using the start() method
        t1.start();
        t2.start();
    }
}
Output
Thread 11 generated 2
Thread 12 generated 10

The SecureRandom class of the java.util package is a cryptographically secure random number generator. It is a subclass of the Random class. A cryptographically secure random number complies with the Statistical Random Number Generator Tests specified in the FIPS 140-2, Security Requirements for Cryptographic Modules, section 4.9.1.  SecureRandom produces a non-deterministic output and this is a necessary requirement for such modules.

Syntax:

public class SecureRandom extends Random

Let us take an example, in the code given below we create an instance of the SecureRandom class and initialize seed value. Next we use a for loop to call the nextInt() method 5 times. The nextInt() method uses the seed value to generate integers from 0 to seed-1 (inclusive). All of this is done inside a try-catch block since it throws an exception when used on any online compiler (Read the Note given below).

Example 

Java




// Java Program to illustrate SecureRandom Class
  
// Importing class from java.security package
import java.security.SecureRandom;
  
// Main class
public class SecureRandomNumbers {
  
    // Main driver method
    public static void main(String[] args)
    {
  
        // Try block to check for exceptions
        try {
  
            // Create an instance of SecureRandom
            // using the default constructor
            SecureRandom r = new SecureRandom();
  
            // Initialise a seed value
            int seed = 100;
  
            System.out.println("Random Numbers");
  
            for (int i = 0; i < 5; i++) {
                // Use the nextInt() method to generate
                // random numbers between 0 and seed-1
                // inclusive
                System.out.print(r.nextInt(seed) + " ");
            }
        }
  
        // Catch block to handle the exceptions
        catch (Exception e) {
  
            System.out.print("Exception");
        }
    }
}
Output
Random Numbers
Exception

Output

Note: The SecureRandom class will not work on an online compiler due to its cryptographically secure nature. However, if you use an IDE on your system you will be able to obtain the output shown in the picture above.




My Personal Notes arrow_drop_up
Recommended Articles
Page :