ps0604 ps0604 - 25 days ago 8
Scala Question

Does Akka cache actor invocation?

I have the following code that I need to run around 100 times:

val system = ActorSystem("mySystem")
val myActorObject = system.actorOf(Props[MyActorClass], name = "myactor")
implicit val timeout = Timeout(60 seconds)
val future = myActorObject ? Request1
val result = Await.result(future, timeout.duration)


Question is: assuming the first two statements can be called just once, should I cache these variables or Akka does it?

Answer

Do not make the actor system creation and actor creation part of repetitive code. Once the actor is created. Using the ActorRef can be used as many times as possible.

val system = ActorSystem("mySystem")
val myActorObject = system.actorOf(Props[MyActorClass], name = "myactor")

Something like this

val futureList = for(_ <- 1 to 1000) yield {
  implicit val timeout = Timeout(60 seconds)
  val future = myActorObject ? Request1
}

val finalF = Future.sequence(futureList)

val result = Await.result(future, timeout.duration)