I am currently working on a scala project, and I decided to use the Akka agent library on the actor model, because it allows a more functional approach to concurrency. However, I have a problem running many different agents at a time. It seems that I will wrap only three or four agents who work immediately.
import akka.actor._ import akka.agent._ import scala.concurrent.ExecutionContext.Implicits.global object AgentTester extends App { // Create the system for the actors that power the agents implicit val system = ActorSystem("ActorSystem") // Create an agent for each int between 1 and 10 val agents = Vector.tabulate[Agent[Int]](10)(x=>Agent[Int](1+x)) // Define a function for each agent to execute def printRecur(a: Agent[Int])(x: Int): Int = { // Print out the stored number and sleep. println(x) Thread.sleep(250) // Recur the agent a sendOff printRecur(a) _ // Keep the agent value the same x } // Start each agent for(a <- agents) { Thread.sleep(10) a sendOff printRecur(a) _ } }
The above code creates an agent holding every integer from 1 to 10. The loop below sends the printRecur function to each agent. The output of the program should show numbers from 1 to 10, which are printed every quarter of a second (although not in any order). However, for some reason, my output only shows numbers with numbers from 1 to 4.
, ? clojure , Scala.
, , , - 1-4. , , , 4 ( ). , , , 4 , , - -.
, :
import scala.concurrent.ExecutionContext.Implicits.global
ActorSystem
import system.dispatcher
, fork, , , , , .
send sendOff, , . , sendOff, , .
send
sendOff