fc.util
Class ThreadLocalRandom
java.lang.Object
fc.util.ThreadLocalRandom
public final class ThreadLocalRandom
- extends java.lang.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.
Method Summary |
java.util.Random |
get()
|
boolean |
isNull()
|
static void |
main(java.lang.String[] args)
|
void |
set(java.util.Random cal)
|
Methods inherited from class java.lang.Object |
equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
ThreadLocalRandom
public ThreadLocalRandom()
get
public java.util.Random get()
set
public void set(java.util.Random cal)
isNull
public boolean isNull()
main
public static void main(java.lang.String[] args)
throws java.lang.Exception
- Throws:
java.lang.Exception