Working With Akka Actors
Here we're going to look at the Akka actor model with a simple example: fetching weather data from Yahoo.
Join the DZone community and get the full member experience.
Join For FreeI am going to explain the Akka actor model with a simple example: fetching weather data from Yahoo. I am going to use the Akka Scala API.
What is Akka?
Akka is a toolkit and runtime for building highly concurrent, distributed, and resilient
message-driven applications on the JVM.
What Is an Actor Model?
Akka has the concept of Actors, which provide an ideal model for thinking about highly concurrent and scalable systems. The actor model is a design pattern for writing concurrent and scalable code that runs on distributed systems.
Why the Actor Model?
Multi-threaded programming runs multiple copies of your application code in their own threads and then synchronizes access to any shared objects. While it’s a complex issue, multi-threaded programming has three major faults:
- Shared objects – protected by synchronized block or method but blocking
- Deadlock – first thread tries to access synchronized block of second thread, while second thread tries to access synchronized block from first thread, resulting in deadlock
- Scalability – managing threads on multiple JVMs.
While the Actor Model is not new and has long existed in Haskell and Erlang, the Akka runtime makes it fairly straightforward to write actor-based applications.
The Actor Model: Why Now?
A lot has happened in last 20 years, and now not only is it possible to scale up (at high-price), but we can scale out.
The actor model allows you to write scalable software applications in a distributed environment without pulling your hair out.
Inside the Actor Model
Let’s understand how it works
- Actor System: is a glue that wires
Actor
s,ActorRef
s,Dispatchers
, andMailbox
es together. Programmers use theActorSystem
to configure the desired implementation of each of these components. It creates and initializes actors. - Next, the actor creation process is initiated by Sender (usually itself), which invokes actorOf() on ActorSystem and creates a reference of an Actor object. At this time the Actor may not be created/initiated. ActorRef acts as a proxy to the Actor object and provides an interface to communicate with the Actor.
- The Sender Actor (Caller – in this case “actor itself from step 2”) uses ! (bang operator known as tell message pattern – “fire-and-forget,” e.g. send a message asynchronously and return immediately) to tell the receiving Actor about the event (Hi Actor, Can you please process this event?).
- ActorRef in response dispatches the event on MessageDispatcher (you can configure ActorSystem to use specific dispatcher by invoking withDispatcher).
- MessageDispatcher enqueues the event to the MessageQueue.
- A MessageQueue is one of the core components in forming an Akka Mailbox.
- MessageQueue is where the normal messages that are sent to Actors will be enqueued (and subsequently dequeued).
- MessageQueue.enqueue() – enqueue the message to this queue, or throw an exception.
- MessageDispatcher also looks for MailBox (By default every actor has a single mailbox – UnboundedMailbox). The MailBox holds the messages for receiving the Actor. Once it finds the MailBox, MessageDispatcher binds a set of Actors to a thread pool (backed by BlockingQueue) and invokes the MailBox.run() method.
- MessageQueue.dequeue() – dequeue the next message from this queue, return null failing that.
- Eventually, MailBox schedules the task on the Actor, which invokes the receive() method on the Actor.
Example
This assumes you are working on Linux and have Scala + SBT configured and ready to use.
build.sbt
name := "ScalaWorld"
version := "1.0"
scalaVersion := "2.11.8"
libraryDependencies += "com.typesafe.akka" %% "akka-actor" % "2.3.4"
libraryDependencies += "org.scala-lang.modules" % "scala-xml_2.11" % "1.0.5"
RunActors.scala
import akka.actor.{Actor, ActorSystem, Props}
import scala.io.Source
import scala.xml._
class WeatherActor extends Actor {
override def receive: Receive = {
case msg => println (msg)
}
}
object RunActors {
def main(args: Array[String]) {
def getWeatherInfo(id: String) {
val url = "http://weather.yahooapis.com/forecastrss?w=" + id + "&u=c"
val response = Source.fromURL(url).mkString
val xmlResponse = XML.loadString(response)
println(xmlResponse \\ "location" \\ "@city",
xmlResponse \\ "condition" \\ "@temp")
}
val system = ActorSystem("WeatherSystem")
val weatherActor = system.actorOf(Props[WeatherActor], name = "weatheractor")
val start = System.nanoTime
for (id <- 4118 to 4128) { //WOEID - Where On Earth ID
weatherActor ! getWeatherInfo(id.toString())
}
val end = System.nanoTime
println("Time : " + (end - start) / 1000000000.0)
}
}
SBT
cd into you project directory and type sbt
/home/hardik/Downloads/ScalaWorld> sbt
[info] Loading project definition from /home/hardik/Downloads/ScalaWorld/project
[info] Set current project to ScalaWorld (in build file:/home/hardik/Downloads/ScalaWorld/)
> run-main RunActors
[info] Updating {file:/home/hardik/Downloads/ScalaWorld}scalaworld…
[info] Resolving jline#jline;2.12.1 …
[info] Done updating.
[info] Compiling 1 Scala source to /home/hardik/Downloads/ScalaWorld/target/scala-2.11/classes…
[info] Running RunActors
Output: I am querying the Yahoo Weather WebService API and passing WOEID (Where on Earth ID), starting from 4118 to 4128 and fetching City and Temperature information. As you can see I have executed getWeatherInfo() both with and without Actors and you can see the execution time difference.
I only touched the surface of Akka Actors. There is a lot more to cover, which I will cover in next article.
Published at DZone with permission of Hardik Pandya, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments