An Akka actors ‘ask’ example - ask, future, await, timeout, duration, and all that

Akka actor ask FAQ: Can you share an example that shows how one Akka actor can ask another actor for information?

Sure. Here’s a quick Scala example to demonstrate how one Akka actor can ask another Akka actor for some information and wait for a reply. When using this “ask” functionality, you can either use the ask method, or the ? operator, and I show both approaches below:

import akka.actor._
import akka.dispatch.Await
import akka.dispatch.Future
import akka.pattern.ask
import akka.util.Timeout
import akka.util.duration._

case object AskNameMessage

class TestActor extends Actor {
  def receive = {
    case AskNameMessage => // respond to the "ask" request
                           sender ! "Fred"
    case _ => println("that was unexpected")
  }
}

object AskTest extends App {

  // create the system and actor
  val system = ActorSystem("AskTestSystem")
  val myActor = system.actorOf(Props[TestActor], name = "myActor")

  // (1) this is one way to "ask" another actor
  implicit val timeout = Timeout(5 seconds)
  val future = myActor ? AskNameMessage
  val result = Await.result(future, timeout.duration).asInstanceOf[String]
  println(result)

  // (2) this is a slightly different way to ask another actor
  val future2: Future[String] = ask(myActor, AskNameMessage).mapTo[String]
  val result2 = Await.result(future2, 1 second)
  println(result2)

  system.shutdown

}

The future/await syntax is shown in the Akka documentation, but the part I wasn’t sure about was how my TestActor should reply to this request. Should it simply return a String, or should it return a String to the sender using the ! operator? As you can see, using the ! operator is the correct approach.

It's important to note that this example shows a blocking approach, which may not be good for many cases. But in my real-world problem (not shown here), one of my actors needs to query another actor about its state, and with the current design, I need something like this ask/future/timeout/await/result approach to get that state information.

Also note that there might be better ways to approach this problem, and other ways to “ask” another actor about its state, but for today, this is what I know.