Over a million developers have joined DZone.

Working With Akka Actors

Here we're going to look at the Akka actor model with a simple example: fetching weather data from Yahoo.

· Java Zone

Discover how powerful static code analysis and ergonomic design make development not only productive but also an enjoyable experience, brought to you in partnership with JetBrains

I 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


actormodel (2)

Let’s understand how it works

  1. Actor System: is a glue that wires Actors, ActorRefs, Dispatchers, and Mailboxes together. Programmers use the ActorSystem to configure the desired implementation of each of these components. It creates and initializes actors.
  2. 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.
  3. 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?).
  4. ActorRef in response dispatches the event on MessageDispatcher (you can configure ActorSystem to use specific dispatcher by invoking withDispatcher).
  5. MessageDispatcher enqueues the event to the MessageQueue.
    1. A MessageQueue is one of the core components in forming an Akka Mailbox.
    2. MessageQueue is where the normal messages that are sent to Actors will be enqueued (and subsequently dequeued).
    3. MessageQueue.enqueue() – enqueue the message to this queue, or throw an exception.
  6. 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.
  7. MessageQueue.dequeue() – dequeue the next message from this queue, return null failing that.
  8. Eventually, MailBox schedules the task on the Actor, which invokes the receive() method on the Actor.


This assumes you are working on Linux and have Scala + SBT configured and ready to use.


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"


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)


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.

Learn more about Kotlin, a new programming language designed to solve problems that software developers face every day brought to you in partnership with JetBrains.


Published at DZone with permission of Hardik Pandya, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}