In this tutorial, we will write a basic Akka program to create Actors and send messages between actors. First, we add the following dependency of Akka to the pom.xml file:

In Akka, Actors are defined by extending the “Actor” trait and implementing “receive” function. This function consists of case statements that define how Actor handle each received message. The code below is an example of BasicActor: if the Actor receive a String message, it will display the content of the message, the name of sender (using sender().path.name)  as well as the name of the receiver (using self.path.name). In the case if BasicActor receive a message that is not a String format, it will display a warning “Received unknown message!!!”

Akka doesn’t allow users to create actors directly but through ActorSystem with actorOf(props: Props) function or actorOf(props: Props, name: String) (more details about ActorSystem can be found at here). “props” is used to config the properties of the actor while “name” is used to specific the name of actor. The following code describe how to create an actor named “TestActor” and how to send a message to this Actor (“!” is used to send a message. The code actor ! “Hello Akka” means sending a message with content “Hello Akka” to actor)

Run the code, we get the following result (Note: when using  “!” or tell() to send a message, if the message is not sent from an Actor, the sender will be deadLetters by default. In this example, we send a message from the main function, so the sender is deadLetters and the receiver is TestActor):

So, we have finished writing a basic Akka program that define Actors, create actors with ActorSystem and send messages between actors. The full code of this tutorial can be found below.

January 13, 2019
ITechSeeker