How many actors can I run in scala?

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 conclusion

 ++++++++++ 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 am I missing, that only four actors actually begin? Does it depend on my computer? Some configuration? Should I start actors differently? Is it because I run this code inside netbeans?

Thank you very much!

+4
source share
2 answers

I think this is due to the scala actor pool. Probably (I'm still waiting in my book Actors in Scala) creates a four-thread pool (possibly associated with your quad-core processor) and assigns you its actors. The problem is that you are using Thread.sleep . This refers to a specific thread and bypasses the scala actor to the destination of the threads.

+8
source

Scala has essentially two types of participants (using standard Scala 2.8 participants): stream-based and event-based.

When you use receive (or receiveWithin ), as in your example, you create entities based on threads that are relatively heavyweight. There is a separate thread for each actor, which is blocked while 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 lighter; there is no one-to-one communication between participants and event-based streams. You can easily create thousands of event-based contributors.

I wrote a more detailed blog post (and sample application).

+6
source

All Articles