public final class ThreadLocalRandom extends Object
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 and Description |
---|
ThreadLocalRandom() |
Modifier and Type | Method and Description |
---|---|
Random |
get() |
boolean |
isNull() |
static void |
main(String[] args) |
void |
set(Random cal) |