ThreadLocalRandom vs SecureRandom Class in Java
Last Updated :
10 May, 2022
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. The class view is as follows:
--> java.util Package
--> ThreadLocalRandom Class
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.
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 there are 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 required classes
import java.util.concurrent.ThreadLocalRandom;
// Main class
public class ThreadLocalRandomNumbers extends Thread {
// Method 1
// 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");
}
}
// Method 2
// Main driver method
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();
}
}
OutputThread 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 {
// Creating an instance of SecureRandom
// using the default constructor
SecureRandom r = new SecureRandom();
// Initializing a seed value
int seed = 100;
// Display command
System.out.println("Random Numbers");
for (int i = 0; i < 5; i++) {
// Generating random numbers between 0 and
// seed-1 inclusive using nextInt() method
System.out.print(r.nextInt(seed) + " ");
}
}
// Catch block to handle the exceptions
catch (Exception e) {
// Display message when exception occurs
System.out.print("Exception");
}
}
}
OutputRandom 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.
Let us see the differences in a tabular form is as shown below as follows:
ThreadLocalRandom | SecureRandom |
ThreadLocalRandom is a combination of the ThreadLocal and Random classes | SecureRandom class provides a cryptographically strong random number generator |
It is isolated to the current thread. |
Its syntax is -:
public class SecureRandom extends Random
|
it has better performance in a multithreaded environment | SecureRandom implementations are in the form of a pseudo-random number generator |
ThreadLocalRandom doesn't support setting the seed explicitly. Instead | This class does not work in an online compiler. |
It is introduced from jdk 1.7 onwards | SecureRandom class is subclass of Random class. |
Similar Reads
Random vs ThreadLocalRandom Classes in Java
The Random Class of the java.util package is used for generating a stream of pseudorandom numbers. It uses a 48-bit seed, which is amended by implementing a Linear Congruential Formula. The general form of a Linear Congruential Formula is an+1 = k * an + c (mod m) where a0 is the seed, a1, a2, ... a
5 min read
Java.lang.ThreadLocal Class in Java
This class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable. Basically, it is another way to achieve thread safety apart from writing im
4 min read
java.net.SecureCacheResponse Class in Java
The SecureCacheResponse Class in Java represents a cache response originally retrieved through secure means. Syntax: Class Declaration public abstract class SecureCacheResponse extends CacheResponse The constructor for this class is as follows SecureCacheResponse() Now, the methods of this class are
3 min read
Random vs Secure Random numbers in Java
Prerequisite: Generating Random numbers in Javajava.security.SecureRandom class: This class provides a cryptographically strong random number generator (RNG). A cryptographically strong random number minimally complies with the statistical random number generator tests specified in FIPS 140-2, Secur
3 min read
Java.util.Random class in Java
Random class is used to generate pseudo-random numbers in java. An instance of this class is thread-safe. The instance of this class is however cryptographically insecure. This class provides various method calls to generate different random data types such as float, double, int. Constructors: Rando
4 min read
SecureRandom setSeed() method in Java with Examples
setSeed( byte[] seed ) The setSeed() method of java.security.SecureRandom class is used to reseeds this random object. The given seed supplements, rather than replaces, the existing seed. Thus, repeated calls are guaranteed never to reduce randomness. Syntax: public void setSeed(byte[] seed) Paramet
4 min read
java.lang.management.ThreadInfo Class in Java
java.lang.management.ThreadInfo class contains methods to get information about a thread. This information includes: Thread IDThread NameState of the ThreadStack trace of the ThreadThe object upon which the Thread is blockedList of object monitors that are blocked by the ThreadList of ownable synchr
4 min read
SecureRandom getSeed() method in Java with Examples
The getSeed() method of java.security.SecureRandom class is used to return the given number of seed bytes, computed using the seed generation algorithm that this class uses to seed itself. This call may be used to seed other random number generators. This method is only included for backward compati
2 min read
Class Level Lock in Java
Every class in Java has a unique lock which is nothing but class level lock. Â If a thread wants to execute a static synchronized method, then the thread requires a class level lock. Class level lock prevents multiple threads to enter a synchronized block in any of all available instances of the clas
5 min read
Java.lang.Void Class in Java
Java.lang.Void class is a placeholder that holds a reference to a class object if it represents a void keyword. It is an uninstantiable placeholder. Well, uninstantiable means that this class has a private constructor and no other constructor that we can access from outside. Methods of lang.void cla
1 min read