DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
11 Monitoring and Observability Tools for 2023
Learn more
  1. DZone
  2. Coding
  3. Java
  4. Java 7's ThreadLocalRandom

Java 7's ThreadLocalRandom

Dustin Marx user avatar by
Dustin Marx
·
Jan. 09, 12 · Interview
Like (0)
Save
Tweet
Share
8.31K Views

Join the DZone community and get the full member experience.

Join For Free

Java 7 brings many new language features and new classes to the Java developer. One of the new classes included in Java 7's new concurrency offerings is ThreadLocalRandom (located in the java.util.concurrent package). ThreadLocalRandom extends java.util.Random, but intentionally does not support the explicit setting of seed its parent class supports.

ThreadLocalRandom prohibits explicit setting of its seed by overriding Random's setSeed(long) method and automatically (always) throwing an UnsupportedOperationException if called. Although ThreadLocalRandom encourages more true randomness by prohibiting explicit seeds, this can be achieved in Random by simply avoiding explicit setting of seeds. The real advantage that ThreadLocalRandom brings is performance in concurrent applications.

The Javadoc documentation for the java.util.Random class states, "Instances of java.util.Random are threadsafe. However, the concurrent use of the same java.util.Random instance across threads may encounter contention and consequent poor performance. Consider instead using ThreadLocalRandom in multithreaded designs." The Javadoc documentation for java.util.concurrent.ThreadLocalRandom expands on this:

A 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. When applicable, use of ThreadLocalRandom rather than shared Random objects in concurrent programs will typically encounter much less overhead and contention. Use of ThreadLocalRandom is particularly appropriate when multiple tasks (for example, each a ForkJoinTask) use random numbers in parallel in thread pools.

The ThreadLocalRandom class is easy to use and one approach is shown in the next code listing. The code listing provides enough methods to compare Random to ThreadLocalRandom using an explicit seed in each case and relying on implicit seeding in each case.

package dustin.examples;

import static java.lang.System.out;

import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

/**
 * Simple demonstration of Random and ThreadLocalRandom.
 * 
 * @author Dustin
 */
public class Main
{
   /**
    * Provide a random integer.
    * 
    * @return Random integer.
    */
   public int getRandomInteger()
   {
      final Random random = new Random();
      return random.nextInt();
   }

   /**
    * Provide a random integer using provided seed.
    * 
    * @param newSeed Seed to be used in acquiring random integer.
    * @return Random integer.
    */
   public int getRandomIntegerUsingProvidedSeed(final int newSeed)
   {
      final Random random = new Random(newSeed);
      return random.nextInt();
   }

   /**
    * Provide a random integer using ThreadLocalRandom. Note that it has no
    * constructor.
    * 
    * @return Random integer.
    */
   public int getThreadLocalRandomInteger()
   {
      return ThreadLocalRandom.current().nextInt();
   }

   /**
    * Demonstrates that attempting to set the seed for a ThreadLocalRandom
    * instance results in an UnsupportedOperationException.
    * 
    * @param newSeed Seed to attempt to use with ThreadLocalRandom.
    * @return Would return random integer, but should never reach this because
    *    UnsupportedOperationException should occur when attempting to set
    *    provided seed.
    * @throws UnsupportedOperationException This exception is always thrown!
    */
   public int getThreadLocalRandomIntegerUsingProvidedSeed(final int newSeed)
   {
      final ThreadLocalRandom random = ThreadLocalRandom.current();
      random.setSeed(newSeed);
      return random.nextInt();
   }

   /**
    * Run examples.
    * 
    * @param arguments Command-line arguments; none expected.
    */
   public static void main(final String[] arguments)
   {
      final int sampleSeed = 15;
      final Main me = new Main();
      out.println("Random Integer: " + me.getRandomInteger());
      out.println("Seeded Random Integer: " + me.getRandomIntegerUsingProvidedSeed(sampleSeed));
      out.println("Thread Local Random Integer: " + me.getThreadLocalRandomInteger());
      out.println(  "Seeded Thread Local Random Integer: "
                  + me.getThreadLocalRandomIntegerUsingProvidedSeed(sampleSeed));
   }
}

The next screen snapshot shows the output of running the above code twice. The output demonstrates that using the same seed leads to the same "random" integer when using Random. It also demonstrates that ThreadLocalRandom does not allow the explicit setting of a seed. Unlike Random, the ThreadLocalRandom class does not provide a constructor taking the seed (in fact, it provides no constructor at all). With no constructor accepting a seed, the setSeed(long) method declared by parent Random class was the remaining approach for setting a seed explicitly. ThreadLocalRandom shuts this option down via the overridden implementation that throws the UnsupportedOperationException.

ThreadLocalRandom is a simple addition to the Java SDK, but is an improvement that can occasionally be welcome when using random numbers in highly concurrent applications.

 

From http://marxsoftware.blogspot.com/2011/12/java-7s-threadlocalrandom.html

Java (programming language)

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • How to Submit a Post to DZone
  • DZone's Article Submission Guidelines
  • Unlocking the Power of Elasticsearch: A Comprehensive Guide to Complex Search Use Cases
  • Create a REST API in C# Using ChatGPT

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: