3

May I use the same scala.util.Random object in multiple threads?

Tomer Shetah
  • 8,413
  • 7
  • 27
  • 35
  • 2
    Looking at the [source code](https://github.com/scala/scala/blob/master/src/library/scala/util/Random.scala), it just uses `java.util.Random` which IIRC has been thread-safe since J2SE 1.4 or 1.5 (the 1.4 docs say it uses AtomicLong, but that was only added in 1.5). – tc. Mar 07 '13 at 01:10

2 Answers2

5

One of the important features of a PRNG is repeatability when given the same seed. Imagine your code hits an exception or crashes when you launch it. You want to repeat that behavior so you can debug the issue. If you give yourself control of the seed you can launch the program with the same seed over and over while you debug the problem. If you access the generator from a single thread it will see the same sequence for a given seed. If you access it from many threads you will not be able to control the order that each thread gets access to the generator and thus they will see different subsets of the sequence. So you may not want to take advantage of the thread safety of Random even if you can rely on it.

Ben Jackson
  • 90,079
  • 9
  • 98
  • 150
  • 1
    Very good point! Never thought of that. I'd say for this situation, yes it is thread safe, but if you're relying on being able to "replay" the code (which Random doesn't really lend itself to usually, as you'll want a random number right?) your point is very valid. – Christian Stewart Mar 06 '13 at 23:47
  • 1
    Thank you. If I understood your answer properly, you mean scala.util.random is safe to use on multiple threads, but may be difficult to debug in this scenario. –  Mar 07 '13 at 20:14
0

I completely agree with @BenJackson, but I think that it is important to mention that scala.util.Random is thread safe. As @tc. mentioned in the comment, scala.util.Random is just a wrapper to java.util.Random. As elaborated in many answers to Is Random class thread safe? it is shown that it is thread safe, but in this comment there is a link to javadoc that states:

Instances of java.util.Random are threadsafe. However, the concurrent use of the same java.util.Random instance across threads may encounter contention and consequent poor performance. Consider instead using ThreadLocalRandom in multithreaded designs.

Therefore, as long as you use JDK version 7 or higher, it is thread safe.

Tomer Shetah
  • 8,413
  • 7
  • 27
  • 35