Book Image

Akka Cookbook

By : Vivek Mishra, Héctor Veiga Ortiz
Book Image

Akka Cookbook

By: Vivek Mishra, Héctor Veiga Ortiz

Overview of this book

Akka is an open source toolkit that simplifies the construction of distributed and concurrent applications on the JVM. This book will teach you how to develop reactive applications in Scala using the Akka framework. This book will show you how to build concurrent, scalable, and reactive applications in Akka. You will see how to create high performance applications, extend applications, build microservices with Lagom, and more. We will explore Akka's actor model and show you how to incorporate concurrency into your applications. The book puts a special emphasis on performance improvement and how to make an application available for users. We also make a special mention of message routing and construction. By the end of this book, you will be able to create a high-performing Scala application using the Akka framework.
Table of Contents (18 chapters)
Title Page
Credits
About the Authors
About the Reviewer
www.PacktPub.com
Customer Feedback
Preface

Sending messages to actors


Sending messages to actors is the first step for building a Akka based application as Akka is a message driven framework, so get started

Getting ready

In this recipe, we will learn how to send messages to actors. Prerequisites are the same as the previous recipes.

How to do it...

In the previous recipe, we created an actor which calculates the sum of integers:

        val actor = actorSystem.actorOf(Props[SummingActor],
          "summingactor") 

Now, we will send messages as integers to the summing actor, as follows:

        actor ! 1 

The following will be the output:

My state as sum is 1

If we keep on sending messages inside a while loop, the actor will continue to calculate the sum incrementally:

        while (true) { 
          Thread.sleep(3000) 
          actor ! 1 
        } 

On sending messages inside a while loop, the following output will be displayed:

my state as sum is 1
my state as sum is 2
my state as sum is 3
my state as sum is 4
my state as sum is 5

If we send a string message Hello, this message will fall into the actor's default behavior case, and the output will be as follows:

I don't know what you are talking about

How it works...

Actors have methods to communicate with each other actors like tell (!) or ask (?) where the first one is fire and forget and the second returns a Future which means the response will come from that actor in the future.

As soon as you send the message to the actor, it receives the message, picks up an underlying Java thread from the thread pool, does it's work, and releases the thread. The actors never block your current thread of execution, thus, they are asynchronous by nature.

There's more...

Visit the following link to see more information on send messages:

http://doc.akka.io/docs/akka/current/scala/actors.html#Send_messages.