Class ThreadLocalRandom
java.lang.Object
fc.util.ThreadLocalRandom
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:
Note, the lines in red are always needed anywhere/anytime this class is used.//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();
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
Constructors -
Method Summary
-
Constructor Details
-
ThreadLocalRandom
public ThreadLocalRandom()
-
-
Method Details
-
get
-
set
-
isNull
-
main
-