Skip to content

Instantly share code, notes, and snippets.

@ajantis
Last active January 4, 2016 20:10
Show Gist options
  • Save ajantis/8672620 to your computer and use it in GitHub Desktop.
Save ajantis/8672620 to your computer and use it in GitHub Desktop.
Akka actor dispatcher and nested futures
import akka.actor._
import scala.concurrent.duration._
import scala.concurrent.Future
object MyApp extends App {
val actorSystem = ActorSystem()
val myActor = actorSystem.actorOf(Props[MyActor])
myActor ! "Hello!"
}
class MyActor extends Actor with ActorLogging {
import context.dispatcher // This causes the second future to fail during intialization with NPE because dispatcher is a 'def' inside of an actor
//implicit val ctx = context.dispatcher // This works as we "capture" execution context by eagerly evaluating it while actor is still alive
context.setReceiveTimeout(2.seconds)
def receive = {
case ReceiveTimeout =>
println("Receive timeout! Stopping...")
context.stop(self)
case msg: String =>
println(s"Received a message: $msg")
Future {
Thread.sleep(3000) // 3 seconds
} onComplete {
case _ =>
println("First future is done.")
Future { // a nested future. Initialization may fail with NPE: ERROR [Dispatcher]: java.lang.NullPointerException: null
Thread.sleep(1000)
} onComplete {
case _ =>
println("Second future is done.")
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment