dimo414 dimo414 - 1 year ago 75
Java Question

Should I prefer ThreadLocalRandom over ThreadLocal<Random>?

I'm looking to use (seeded)

objects across multiple threads, and the javadocs pointed me to
which looks great except I can't set the seed, so I can't ensure consistency among different threads or runs. Is there any practical reason to use
or would it be acceptable to do something like the following:

// Pass returned ThreadLocal object to all threads which need it
public static ThreadLocal<Random> threadRandom(final long seed) {
return new ThreadLocal<Random>(){
protected Random initialValue() {
return new Random(seed);

Answer Source

You can simply use Random, just make sure each Random object is only accessed within a single thread.

Random, being an ancient class like Vector, is unnecessarily heavily synchronized. They probably wanted to show off Java's threading support since it was a big deal at that time. Also Java was mostly intended to run on consumer PCs which mostly had a single processor so synchronization didn't impact scaling like it does today on multiprocessors.

Now an obvious answer is to provide a thread-unsafe version of Random, just like providing the thread-unsfae ArrayList as the alternative to Vector. That didn't happen, instead, we got ThreadLocalRandom. That is kind of odd, not sure what's the motivation behind that. In java8, ThreadLocalRandom is further optimized to operate directly on some int fields in the Thread object.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download