Akka, a free open source toolkit simplifying the construction of concurrent and distributed system/application. In this blog we are gonna discussing about Akka, Actors and finally creating and running our first actor.
Again, it is a free and open-source toolkit and runtime. It is used to develop highly concurrent, distributed, and fault-tolerant message-driven applications on the JVM(Java Virtual Machine).
It includes features for both local as well as remote distribution. We are not gonna discuss the remote distribution but we’ll discuss about local i.e. limited to a single JVM.
Akka Actors –
The Actor Model provides an elevated level of abstraction concurrent and distributed systems. It takes the edge off the developer from having to deal with explicit locking and thread management thus making it easier to write concurrent and parallel systems.
An Actor represents an independent computational unit that encapsulates its state and part of the application logic.
Actors are objects and you can’t access them directly rather, but only send messages to. In other words they interact only through asynchronous messages and never through direct method calls.
Life Cycle of Akka Actors –
So life cycle of an Actor automatically starts after its instantiation. An Actor after its instantiation straight off start processing messages. When a failure occurs then some hooks like preRestart() and postRestart() takes place. These hooks are called whenever an actor is restarted by its supervisor/parent upon failure.
Let’s look into it’s life cycle visualising the same.
Creating and Running First Actor –
There are a number of steps which we need to follow in order to create and run our first actor which includes the following –
- Define your Actor System
- Create Actor
- Instantiate your Actor
- Communicate with Actor
Let’s implement the same …
Add the Dependencies –
Add the following dependencies in the “build.sbt”.
Defining An Actor System –
Start with defining your Actor System and validating it by printing your actor system name.
Creating Actor –
Create your actor by extending the Actor trait and override method receive which actually is a partial function.
Instantiating the Actor –
Instantiate your actor through your actor system. We use actorOf Method having two parameters Props(reference of your actor) and your actor name which is optional.
Communicating with Actor –
Actor Communicates through messages (Asynchronous). We use “!” to communicate with actor and this symbol is known as Bang or Tell.
Now, Let’s integrate all steps and try running our first actor.
Stay Tunes ..
In this Blog we have discussed an overview of Scala and thus creating our first actor. Stay Tuned for more blogs …