Should I prefer ThreadLocalRandom over ThreadLocal<Random>?

concurrency, java, random

Solution

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.

Problem

I'm looking to use (seeded) `Random` objects across multiple threads, and the javadocs pointed me to `ThreadLocalRandom` 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 `ThreadLocalRandom` 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>(){ @Override protected Random initialValue() { return new Random(seed); } }; } ```

Original source