Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This seems like a duplicate of another question. So I'll duplicate my answer</p> <p>Actors process one message at a time. The classic pattern to process multiple messages is to have one coordinator actor front for a pool of consumer actors. If you use react then the consumer pool can be large but will still only use a small number of JVM threads. Here's an example where I create a pool of 10 consumers and one coordinator to front for them.</p> <pre><code>import scala.actors.Actor import scala.actors.Actor._ case class Request(sender : Actor, payload : String) case class Ready(sender : Actor) case class Result(result : String) case object Stop def consumer(n : Int) = actor { loop { react { case Ready(sender) =&gt; sender ! Ready(self) case Request(sender, payload) =&gt; println("request to consumer " + n + " with " + payload) // some silly computation so the process takes awhile val result = ((payload + payload + payload) map {case '0' =&gt; 'X'; case '1' =&gt; "-"; case c =&gt; c}).mkString sender ! Result(result) println("consumer " + n + " is done processing " + result ) case Stop =&gt; exit } } } // a pool of 10 consumers val consumers = for (n &lt;- 0 to 10) yield consumer(n) val coordinator = actor { loop { react { case msg @ Request(sender, payload) =&gt; consumers foreach {_ ! Ready(self)} react { // send the request to the first available consumer case Ready(consumer) =&gt; consumer ! msg } case Stop =&gt; consumers foreach {_ ! Stop} exit } } } // a little test loop - note that it's not doing anything with the results or telling the coordinator to stop for (i &lt;- 0 to 1000) coordinator ! Request(self, i.toString) </code></pre> <p>This code tests to see which consumer is available and sends a request to that consumer. Alternatives are to just randomly assign to consumers or to use a round robin scheduler. </p> <p>Depending on what you are doing, you might be better served with Scala's Futures. For instance, if you don't really need actors then all of the above machinery could be written as</p> <pre><code>import scala.actors.Futures._ def transform(payload : String) = { val result = ((payload + payload + payload) map {case '0' =&gt; 'X'; case '1' =&gt; "-"; case c =&gt; c}).mkString println("transformed " + payload + " to " + result ) result } val results = for (i &lt;- 0 to 1000) yield future(transform(i.toString)) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload