In this tutorial, we will write a program that demonstrates the life cycle of an Akka actor by overriding the following four functions: preStart(), preRestart(), postStop() and postRestart().The use of these four functions can be described using the following chart (Note: preRestart() is called by the old instance while postRestart() is called by the new one. By default,  preRestart() dismiss all children of the old instance, then call the postStop() function while the postRestart() function will call preStart()):

First, we define the LifeCycleActor by re-using the code presented on the tutorial Writing a basic Akka program. However, in the default case, we will raise an Exception instead of displaying a warning “Received unknown message!!!” (to illustrate the process of restarting Akka Actor):

To override four functions: preStart(), preRestart(), postStop() and postRestart(), we can do as follows:

To check the operation of the above four functions, we send two messages: one is a normal message (in String format) and the other is an message that raise an Exception (not in String format):

Run the code, we get the following result:

In the case when Actor receive a String message, only preStart() function is called. However, if the Exception occurs, all four functions are called with the following order: preRestart is called to delete the old instance and then it calls postStop() function. After the postStop() function is executed, postRestart() an preStart() are in turn called by the newly created instance. Similarly, when we stop the actor, the postStop() function is used to release all resources of that actor.

So, we have finished writing a program that use four functions: preStart(), preRestart(), postStop() and postRestart() to illustrate the life cycle of an Akka actor. The full code of this tutorial is provided below:

January 13, 2019
ITechSeeker