DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Distributing Data and Logic: Enhancing Performance, Resilience, and Efficiency With Akka
  • All the Cloud’s a Stage and All the WebAssembly Modules Merely Actors
  • Writing a Chat With Akka
  • Video Streaming With Akka Streams

Trending

  • AWS to Azure Migration: A Cloudy Journey of Challenges and Triumphs
  • Unlocking AI Coding Assistants: Generate Unit Tests
  • Agentic AI for Automated Application Security and Vulnerability Management
  • MySQL to PostgreSQL Database Migration: A Practical Case Study
  1. DZone
  2. Coding
  3. Java
  4. Working With Akka Actors

Working With Akka Actors

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

By 
Hardik Pandya user avatar
Hardik Pandya
·
May. 18, 16 · Tutorial
Likes (10)
Comment
Save
Tweet
Share
12.1K Views

Join the DZone community and get the full member experience.

Join For Free

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.

past_present.png

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.

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.

Akka (toolkit)

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

Opinions expressed by DZone contributors are their own.

Related

  • Distributing Data and Logic: Enhancing Performance, Resilience, and Efficiency With Akka
  • All the Cloud’s a Stage and All the WebAssembly Modules Merely Actors
  • Writing a Chat With Akka
  • Video Streaming With Akka Streams

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: