How many actors can be launched in scala?

浪尽此生 提交于 2019-12-06 06:45:36

问题


I tried this code

import scala.actors.Actor

class MyActor(val id:Int) extends Actor {
    def act() {
        println (" ****************** starting actor: " + id)

        while (true) {
            Thread.sleep(1000);
            println ("I'm actor " + id)
        }
    }
}

object Main {
    def main(args:Array[String]) {
        val N = 5
        for (i leftArrow 1 to N) {
            val a = new MyActor(i)
            println (" ++++++++++ about to start actor " + a.id)
            a.start
        }

        println (N + " actors launched?")
    }
}

and got this output

++++++++++ about to start actor 1
 ++++++++++ about to start actor 2
 ++++++++++ about to start actor 3
 ++++++++++ about to start actor 4
 ++++++++++ about to start actor 5
5 actors launched?
 ****************** starting actor: 1
 ****************** starting actor: 4
 ****************** starting actor: 3
 ****************** starting actor: 2
I'm actor 4
I'm actor 3
I'm actor 1
I'm actor 2
I'm actor 4

So, what I'm missing that only four actors are actually being started? Does it depend on my computer? Some configuration? Should I start actors in a different way? Is it because I'm running that code inside netbeans?

Thank you very much !


回答1:


I think it has to do with scala´s actor pool. It probably (I am still waiting on my book "Actors in Scala") creates a pool with four threads (perhaps related to your four core CPU) and assigns your actors to them. The problem is, that you use Thread.sleep. That appeals to a certain thread and bypasses scala´s actor to thread assignment.




回答2:


There are essentially two kinds of actors in Scala (when using the standard Scala 2.8 actors): thread-based and event-based actors.

When you use receive (or receiveWithin), as in your example, you are creating thread-based actors, which are relatively heavyweight. There's a separate thread for each actor, which is blocked as long as the actor is waiting for a message.

When you use react instead of receive, your actor will be an event-based actor. Event-based actors are much more lightweight; there is not a one-to-one link between event-based actors and threads. You can easily create thousands of event-based actors.

I've written a blog post (and example application) with more detail.



来源:https://stackoverflow.com/questions/5848299/how-many-actors-can-be-launched-in-scala

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