Sending messages to actors is the first step for building a Akka based application as Akka is a message driven framework, so get started
Sending messages to actors
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.