Allen Han
Allen Han

Reputation: 1163

What is the default timeout for Ask in Akka?

What is the default value for the timeout of Ask in Akka?

All that is necessary to use the ask method in Akka is to import akka.pattern.ask. In the docs, there are examples of ask where no timeout is supplied either directly or as an implicit val.

https://doc.akka.io/docs/akka/2.5/actors.html

I have read the source for ask myself and cannot find a default value supplied for the timeout. However, the ask method works fine even when no timeout is supplied, meaning a default value is used, somewhere.

What is this default value, and how is it supplied to ask?

Upvotes: 1

Views: 4966

Answers (2)

senjin.hajrulahovic
senjin.hajrulahovic

Reputation: 3191

If you take a look at the class akka.pattern.AskableActorRef you'll see that the ask method has an implicit Timeout parameter. This means that there must be a Timeout instance defined implicitly somewhere or you pass is explicitly. Otherwise it wouldn't work.

protected def ?(message: Any)(implicit timeout: akka.util.Timeout): Future[Any]

In your case the Timeout is most likely resolved with implicit lookup. Try to use the laws of implicit lookup to find the instance.

Implicit lookup

Upvotes: 0

Allen Han
Allen Han

Reputation: 1163

There is no default timeout. A specific timeout value must be supplied to ask either by manually passing it in or by using an implicit val. In the second case, the implicit val may not necessarily appear in the same file where the ask is used, depending on what other namespaces the ask can see when it is being called.

I copied some code from Akka Cookbook that looks like follows

import akka.actor.{Actor, Props, ActorSystem}
import akka.pattern.ask
import akka.util.Timeout
import scala.concurrent.Await
import scala.concurrent.duration._

class FibonacciActor extends Actor {
  override def receive: Receive = {
    case num : Int =>
      val fibonacciNumber = fib(num)
      sender ! fibonacciNumber
  }

  def fib (n : Int) : Int = n match {
    case 0 | 1 => n
    case _ => fib(n-1) + fib(n-2)
  }
}

object FibonacciActorApp extends App {
  implicit val timeout = Timeout(3.seconds)
  val actorSystem = ActorSystem("HelloAkka")
  val actor = actorSystem.actorOf(Props[FibonacciActor])
  val future = (actor ? 10).mapTo[Int]
  val fibonacciNumber = Await.result(future, 10 seconds)
}

The code will not compile without a supplied Timeout value.

What is happening is that I am at work looking at some code that does not appear to supply a timeout in the same file where the ask is being called. The timeout appears as an implicit val in the larger namespace where my file is being called. So a timeout has to be supplied, but depending on the codebase, that timeout may not be in the same file where the ask is called. I found the place where the timeout appears by searching my codebase for all uses of the akka.util.Timeout class.

Upvotes: 3

Related Questions