Hi
For testing purposes I wrote a small program to compute fibonacci numbers
the program fails (not enough memory) for fibonacci 34
fibonacci 34 creates 18454929 actors
Using a common Lisp implementation of a classical Actor model I could compute fibonacci 34 in around 22 seconds (sbcl 8GB, 24 cores), I want to understand why the Scala/Akka program fails to compute fibonacci 34 on the same computer
Kind regards
Taoufik
The code:
import akka.actor.{Actor, ActorSystem, Props}
import akka.pattern.ask
import akka.util.Timeout
import scala.concurrent.Await
import scala.concurrent.duration._
class FibonacciActor extends Actor {
def receive: Receive = {
case ("compute", n: Int) if n == 0 || n == 1 =>
sender() ! ("result", n)
case ("compute", n: Int) =>
val worker1 = context.actorOf(Props[FibonacciActor])
val worker2 = context.actorOf(Props[FibonacciActor])
val originalSender = sender()
worker1 ! ("compute", n - 1)
worker2 ! ("compute", n - 2)
context.become {
case ("result", x: Int) =>
context.become {
case ("result", y: Int) =>
originalSender ! ("result", x+y)
}
}
case ("result", r: Int) =>
sender() ! r
}
}
class MainActor extends Actor {
implicit val timeout: Timeout = Timeout(60.seconds)
implicit val ec = context.system.dispatcher
def receive: Receive = {
case n: Int =>
val worker = context.actorOf(Props[FibonacciActor], name = "FibonacciActor")
val start = System.currentTimeMillis()
(worker ? ("compute", n)).mapTo[(String, Int)].foreach {
case ("result", x) =>
println(x, System.currentTimeMillis() - start)
context.system.terminate()
}
case _ => println("Error: message not recognized")
}
}
object Main extends App {
val system = ActorSystem("HelloSystem")
println("start")
implicit val timeout: Timeout = Timeout(60.seconds)
val start = System.currentTimeMillis()
val workers = for (i <- 1 to 1) yield {
val worker = system.actorOf(Props[MainActor], name = "Main"+i)
worker ! 34
worker
}
Await.result(system.whenTerminated, Duration.Inf)
println(System.currentTimeMillis() - start)
}