Here in this blog, I am going to explain what is Akka Actor is and how to implement Akka Actor in your project.
What is Akka
Akka is a free and open-source toolkit and runtime that simplifies the creation of concurrent and distributed applications on the JVM. Akka supports several programming models for concurrency. it emphasizes actor-based concurrency. It is very useful for writing server-side scalable applications. Using Akka, it is very easy to send messages to different nodes of your application. In simple language, you can run your application in multiple numbers. Akka will handle its traffic according to the weight of the machines.
In short, Akka is a convenient framework for performing responsive and distributed applications on the JVM. It is based on the reactive manifesto and so it is :
Event-driven with message passing (i.e loosely coupled).
Resilient through the use of supervision strategies, deathwatch, and hierarchies.
scalable and responsive thanks to saving resources with your actors sharing threads in a non-blocking way. Before, when you were challenged with concurrency problems, you used to have locking mechanisms blocking the current thread and context switching.
What is an Akka Actor:
An actor is an entity that communicates by passing messages to another actor. The actor has his own state and behavior. As in object-oriented programming, everything is an object just as in an actor-based system everything is an actor. In other words, we can say that an actor is an object that encapsulates state and behavior.
Messages can be sent from an actor to an actor using one of the following syntax protocols:
!
(“tell”) – Sends the message and returns immediately.?
(“ask”) – Sends the message and returns a future representing a possible reply.
How to create an Actor:
In Scala, we can create an actor by extending the Actor trait and implementing its get method. This method is called every time the actor receives a message. The receive method does pattern matching on the message received and decides what to do. The actor has a mailbox in which his incoming messages are delivered. There are several mailbox implementations from which to choose, the default implementation is FIFO.
The following useful information is provided to each actor to perform their tasks through the Akka Actors API:
sender
: anActorRef
to the sender of the message currently being processed.context
: information and methods relating to the context within which the actor is running (includes, for example, anactorOf
method for instantiating a new actor).supervisionStrategy
: It defines the strategy used to recover from errors
Let’s see how to write the “Hello Akka” program:
To use Akka Actors, add the following dependency in your build. sbt file:
val AkkaVersion = "2.6.16"
libraryDependencies ++= Seq(
"com.typesafe.akka" %% "akka-actor-typed" % AkkaVersion,
"com.typesafe.akka" %% "akka-actor-testkit-typed" % AkkaVersion % Test
)
Hello Akka Example
import akka.actor.Actor;
import akka.actor.ActorSystem;
import akka.actor.Props;
class HelloAkka extends Actor{
def receive = {
case msg:String => println(msg)
case _ =>println("Unknown message")
}
}
object Main{
def main(args:Array[String]){
var actorSystem = ActorSystem("ActorSystem");
var actor = actorSystem.actorOf(Props[HelloAkka],"Hello Akka")
actor ! "Hello Akka"
actor ! 100.52
}
}
In the above example, we have created an actor “HelloAkka” and extended the Actor trait, and overrode the receive method. You must provide matching cases for all received messages. In case, if there is an unknown message, you need to provide a default case as we did in the above example.
How to Stop an Actor:
There are several ways to stop Akka actors. Actors are the most common ways to call system.stop(actorRef) at the system level or context. stop(actorRef) from within an actor.
There are other ways to stop an actor:
- Send the actor a
PoisonPill
message. - Program a
gracefulStop
.
To demonstrate these options, at the actor system level you can stop the actor by using the actor system instance:
actorSystem.stop(anActor)
Within an actor, you can stop a child actor by using the context
reference:
context.stop(childActor)
An actor can also stop itself:
context.stop(self)
You can stop an actor by sending it a PoisonPill
message:
actor ! PoisonPill
Akka Actor System:
The actor system is a root actor in the actor’s structure. An actor system is a hierarchical group of actors that share a common configuration, e.g. Dispatcher, Deployment, Remote Capabilities, and Addresses. It is also the entry point for creating or viewing actors. It is an abstract class that extends the ActorRefFactory attribute. We can think of the ActorSystem as a ‘black box’ that will eventually hold your actors, and allow you to interact with them.
As a reminder, the actor model passes the message on as a first-class citizen. If the actor model is still unclear at the moment, that’s okay. I will demonstrate how to design a protocol that our actors will understand and react to.
The ActorSystem provides an ActorOf() method that is used to create an Actor instance:
Components of Akka Actor System:
1.) Dead Letter Office
Messages that cannot be delivered will be delivered to actors called dead letters. Messages sent through untrusted networks will be lost without forwarding to the Dead Letter Office. The main use of this feature is for debugging purposes, especially if the message sent by an actor does not arrive consistently. You can implement this by importing akka.actor.DeadLatter package.
2.) User Guardian Actor:
It is a native actor of actors created by the user using the actor system. This particular parent is used to achieve a sequential shutdown sequence where logging remains active while all normal actors are terminated. It monitors all user-generated actors.
3.) System Guardian Actor:
This actor works the same way as the user parent actor except that it works for system actors. The system monitors the parent user parent and initiates its shut-down upon receipt of the finished message.
4.) Scheduler:
A scheduler is an attribute and extends AnyRef. Scheduler handles scheduled tasks. It provides the facility to schedule messages. You can schedule the sending of messages and the execution of tasks. This creates a new instance for each actor system to schedule tasks to happen at a specific time. It returns a Cancellable context so that you can cancel the execution of the scheduled operation by calling the cancel method on this context object.
We can implement a scheduler by importing akka.actor.Scheduler package.
5.) Event System:
The event system, also known as the eventStream, is the main event bus for each ActorSystem.Through this, we stored carry log messages and dead letters. You can also use it to publish messages to the entire actor system. You can get the EventStream context by calling the actorSystemRef.eventStream() method.
6.) Configuration:
ActorSystem provides a configuration component that is used to configure applications. You can access it from your actor system.
Advantages of Akka Actor:
1. It is difficult to develop concurrent applications because we need to deal with synchronization, locks, and shared memory. Using Akka Actors we can easily write asynchronous code without the need for locks and synchronization.
2. One of the advantages of using messages instead of method calls is that the sending thread will not block waiting for a return value when sending a message to another actor. The receiving actor will respond with the result by sending a reply message to the sender.
3. One more incredible benefit of utilizing messages is that we don’t need to stress over synchronization in a multi-string climate.
4. One more benefit of the Akka actor model is dealing with error. Another advantage of the Akka Actor model is error handling. By sorting the actors out of sequence, each actor can tell his parents about the disappointment, so he can act as needed. The parent actor can choose to pause or resume the child actor. The parent actor can choose to stop or restart the child actor.
Conclusion:
In this article, we have covered the basics of the Akka framework. We showed how to define actors, how they communicate with each other, and how to eliminate them. For more blocks Click Here.
References:
https://doc.akka.io/docs/akka/current/typed/actors.html
