Thursday, December 22, 2011

Java 7's ThreadLocalRandom

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.

4 comments:

Turbo said...

I'm a little confused. You cannot seed the ThreadLocalRandom, so it will always return the same random numbers?

So, if I have 5 threads, that use that Main class in the example, all 5 threads will show the pseudorandom number 23565, for example?

What if I need random numbers that are different between Threads? For example to diminish Contention (random sleeps for instance)? Am I stuck with Math.Random in that case?

@DustinMarx said...

Turbo,

Because ThreadLocalRandom "is initialized with an internally generated seed that may not otherwise be modified" and is "like the global Random generator used by the Math class," it should work for the scenario you describe.

I noted that there is a StackOverflow thread ("Java 7: ThreadLocalRandom generating the same random numbers") that discusses the same numbers being created across multiple threads, but that issue turns out to be due to bugs (7051516 and 6955840). I ran the example in the StackOverflow thread and it ran correctly (bugs fixed and generated random numbers do differ across threads) in JDK 1.7.0_02.

Dustin

Turbo said...

Thanks! My fault for not being on the cutting edge of java development.

@DustinMarx said...

A much more detailed look at ThreadLocalRandom is provided in the blog post Java 7: How to write really fast Java code.

Dustin