Search code examples
javamultithreadingrandomconcurrency

ThreadLocalRandom or new Random for each thread


Is there any difference when I create in each thread new java.util.Random object or use the ThreadLocalRandom.current().nextInt(3); ?

From what I've read, ThreadLocalRandom should be used instead of using the same instance of java.util.Random for all threads. But what if I create a new instance for each thread?

When should I use java.util.Random and when ThreadLocalRandom if I need to generate random numbers in multiple threads?

screenshot of source code


Solution

  • If you create your own threads, like you do here, it makes no difference.

    But if your code is called from different threads beyond your control, ThreadLocalRandom is the correct one to use.

    There is one difference that does matter though: for obvious reasons you can't set a seed for ThreadLocalRandom. So if you want to have repeatable sequences, you need to create your own Random instances. (But then if you're running multiple threads, having your RNGs seeded to the same value doesn't always guarantee repeatable behaviour anyway.)

    I would personally use ThreadLocalRandom in all cases where I don't need repeatable sequences.