Вопрос

I'm writing a CPU intensive application built with Akka 2 Futures. I don't need Actors currently but I'm not reluctant to use them.

Several computations enclosed in futures must invoke a random generator, very often. I'm afraid that if I used a classic concurrent RNG, it will become a choking point and I will lose scalability.

What is the most fast/simple way of having a Random generator per thread in the ExecutionContext ?

Is there a way to initialize them all with a different seed (but known in advance) such a to repeat experiment ?

Это было полезно?

Решение

Use akka.jsr166y.ThreadLocalRandom

Другие советы

If using ThreadLocalRandom isn't an option, you can pretty easily write your own using ThreadLocal and Scala's Random. Although providing "additional commonly used bounded random generation methods" is an exercise left to the interested developer.

object ThreadLocalRandom {
  private val localRandom = new ThreadLocal[util.Random] {
    override protected def initialValue() = new util.Random
  }

  def current = localRandom.get
}

Don't use the Scala random generator; it's just a wrapper around Javas which you've probably noticed is synchronized.

Java 7 have a ThreadLocalRandom that is made for your use. If you can't use java 7 use another randomizer; for example the non-synchronized mersenna twister implementation from here: http://www.cs.gmu.edu/~sean/research/. Use this implementation through a ThreadLocal object so that each thread has one thats only initialized once. To seed the instances simply use a shared normal synchronized Random.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top