ThreadLocalRandom Class

A java.util.concurrent.ThreadLocalRandom is a utility class introduced from jdk 1.7 onwards and is useful when multiple threads or ForkJoinTasks are required to generate random numbers. It improves performance and have less contention than Math.random() method.

ThreadLocalRandom Methods

Following is the list of important methods available in the ThreadLocalRandom class.

Sr.No.Method & Description
1public static ThreadLocalRandom current()Returns the current thread’s ThreadLocalRandom.
2protected int next(int bits)Generates the next pseudorandom number.
3public double nextDouble(double n)Returns a pseudorandom, uniformly distributed double value between 0 (inclusive) and the specified value (exclusive).
4public double nextDouble(double least, double bound)Returns a pseudorandom, uniformly distributed value between the given least value (inclusive) and bound (exclusive).
5public int nextInt(int least, int bound)Returns a pseudorandom, uniformly distributed value between the given least value (inclusive) and bound (exclusive).
6public long nextLong(long n)Returns a pseudorandom, uniformly distributed value between 0 (inclusive) and the specified value (exclusive).
7public long nextLong(long least, long bound)Returns a pseudorandom, uniformly distributed value between the given least value (inclusive) and bound (exclusive).
8public void setSeed(long seed)Throws UnsupportedOperationException.

Example

The following TestThread program demonstrates some of these methods of the Lock interface. Here we’ve used lock() to acquire the lock and unlock() to release the lock.

import java.util.Random;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.ThreadLocalRandom;

public class TestThread {
  
   public static void main(final String[] arguments) {
      System.out.println("Random Integer: " + new Random().nextInt());  
      System.out.println("Seeded Random Integer: " + new Random(15).nextInt());  
      System.out.println(
         "Thread Local Random Integer: " + ThreadLocalRandom.current().nextInt());
      
      final ThreadLocalRandom random = ThreadLocalRandom.current();  
      random.setSeed(15); //exception will come as seeding is not allowed in ThreadLocalRandom.
      System.out.println("Seeded Thread Local Random Integer: " + random.nextInt());  
   }
}

This will produce the following result.

Output

Random Integer: 1566889198
Seeded Random Integer: -1159716814
Thread Local Random Integer: 358693993
Exception in thread "main" java.lang.UnsupportedOperationException
        at java.util.concurrent.ThreadLocalRandom.setSeed(Unknown Source)
        at TestThread.main(TestThread.java:21)

Here we’ve used ThreadLocalRandom and Random classes to get random numbers.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *