Akka Futures and Promises
Table of Contents
- Akka gets Futures and Promises from Scala.
0.1 Futures
- A Future is a placeholder object for a result that has not been computed yet. A related CS term is lazy evaluation.
- A Future may only be assigned once. Needs an
ExecutionContext
Invoking the
future
method starts an asynchronous computation and returns a future. The result becomes available once the future completes.import scala.concurrent.{ future, promise } import scala.concurrent.ExecutionContext.Implicits.global val s = socialNetwork.createSessionFor("user", credentials) val f: Future[List[Friend]] = future { s.getFriends() // may take a while }
0.2 Promises
A Promise is a writable, single-assignment container that completes a future. Methods:
success
,failure
,complete
import scala.concurrent.{ future, promise } import scala.concurrent.ExecutionContext.Implicits.global val p = promise[T] val f = p.future val prdcr = future { // producer val r = produceSomething() p . success . r continueDoingSomethingUnrelated() } val cnsmr = future { // consumer startDoingSomething() f . onSuccess { case r => doSomethingWithResult() }}
1 Distributed Actor System
- ./akkaDistributed.html My lecture notes on Distributed Actor System.
2 Termination
What Does "Finished" Mean? The most natural answer to this question appears to be, "When all the Mailboxes are empty." Natural, yes; correct, no. :)
Figure 1: Actor System terminated?
2.1 The Reaper
Figure 2: Actor System Reaper
2.2 Reaper Source Code
import akka.actor.{Actor, ActorRef, Terminated} import scala.collection.mutable.ArrayBuffer object Reaper { case class WatchMe(ref: ActorRef); } abstract class Reaper extends Actor { import Reaper._ val watched = ArrayBuffer.empty[ActorRef] /* Derivations must implement this method. Called * when everything is dead */ def allSoulsReaped(): Unit final def receive = { case WatchMe(ref) => context.watch(ref) watched += ref case Terminated(ref) => watched -= ref if (watched.isEmpty) allSoulsReaped() } }
2.3 PoisonPill
Figure 3: Application with PoisonPill
3 References
- https://doc.akka.io/docs/akka/current/ Nearly all the code snippets and figures are from here. Reference.
- Jonas Boner, "Above the Clouds: Introducing Akka", 2011. Web search. Video or pdf. Highly recommended.
- https://doc.akka.io/docs/akka/current/typed/guide/ Getting Started
Guide. Must visit. The following are linked there.
- Introduction to Akka. Required Reading
- Part 1: Actor Architecture. Required Reading
- Part 2: Creating the First Actor. Required Reading
- Part 3: Working with Device [in the small] Actors Optional Reading
- Part 4: Working with Device Groups Optional Reading
- Part 5: Querying Device Groups Optional Reading
- http://allaboutscala.com/scala-frameworks/akka/ 2020 Recommended Reading.