Strange behavior: Scala Actors 2.7.7 vs. 2.8-Snapshot

不打扰是莪最后的温柔 提交于 2019-12-05 12:35:40

There are some problems with the code. Foremost among them, don't do this:

object ActorApplication extends Application 

When you use extends Application, the way your code is run imposes a number of restrictions, such as not being optimizable by the JIT and, of particular relevance to your case, threads won't work correctly. I find it harder to explain what happened on 2.7.7 than what happened on 2.8. Instead, just write a normal object, and define the main method.

Other stuff:

gearController ! StartSync()

Don't do this. Always send a message to an actor from inside an actor, and this line is inside ActorApplication constructor, which is not an actor. In situations like this, you can do this:

Actor.actor { gearController ! StartSync() }

Speaking of StartSync, don't do this:

case class StartSync

A class without parameters is meaningless (and deprecated). Instead, do this:

case object StartSync

and drop the parenthesis after StartSync in the places where you use it.

Also, there's nothing wrong with scala.util.Random, though it was easier to misuse it on Scala 2.7 than it is on Scala 2.8, by creating a new Random generator every time you needed a random number (which is what you do in the code). Instead, on Scala 2.8, just this ought to work:

  private var mySpeed = scala.util.Random.nextInt(1000)

Finally, there's nothing wrong with either execution, it's just the scheduler that's different between them. In fact, given that you created a hundred actors, the GearController was receiving a disproportional amount of execution time in the Scala 2.7 version, as Scala doesn't create a thread for every actor.

Now, if you want GearController not to share a thread with the others, you should use while(true)/receive instead of loop/react, like this:

    while(true) {
      receive {
        case StartSync => {

Which will produce a result quite similar to what 2.7 produced.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!