Class ThreadLocalRandom

  extended by fc.util.ThreadLocalRandom

public final class ThreadLocalRandom
extends Object

Useful to store thread-local Random instances. This class is intended for servlets/molly pages. Instead of static get/set methods, this class must be instantiated and the instance methods used to get/set the random object. This allows multiple instances of this class in the webapp, with each instance being able to get/set a separate random generator. [If the methods in this class were static, then only 1 random could be get/set per thread].

Each thread must remember to individually create a separate random instance and store it via the set method. The usage idiom is:

//WebApp has a map of ThreadLocalRandoms and also a instance variable
//pointing to a default ThreadLocalRandom
ThreadLocalRandom myrand = WebApp.getThreadLocalRandom("foo");

if (myrand.isNull())  {
        myrand.set(new java.util.Random());

Random rand = myrand.get();

Note, the lines in red are always needed anywhere/anytime this class is used.

The methods in java.util.Random are synchronized (or at least they internally use the synchronized next(int) method), so these ThreadLocalRandoms are really only useful in heavily Multi threaded apps where thread contention over a single random number generator can slow things down.

Constructor Summary
Method Summary
 Random get()
 boolean isNull()
static void main(String[] args)
 void set(Random cal)
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail


public ThreadLocalRandom()
Method Detail


public Random get()


public void set(Random cal)


public boolean isNull()


public static void main(String[] args)
                 throws Exception