0% found this document useful (0 votes)
16 views63 pages

5CS022 Lecture 3

The document discusses the Actor Model as a solution for concurrent programming in distributed systems and cloud computing, emphasizing its advantages over traditional threading models. It outlines the properties of actors, including message immutability, mailboxes, and actor references, as well as the roles of supervisors and the Akka framework that implements the Actor Model. Additionally, it covers actor communication, lifecycle, and failure recovery strategies, highlighting the benefits of building scalable and resilient applications.

Uploaded by

np03cs4a230131
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views63 pages

5CS022 Lecture 3

The document discusses the Actor Model as a solution for concurrent programming in distributed systems and cloud computing, emphasizing its advantages over traditional threading models. It outlines the properties of actors, including message immutability, mailboxes, and actor references, as well as the roles of supervisors and the Akka framework that implements the Actor Model. Additionally, it covers actor communication, lifecycle, and failure recovery strategies, highlighting the benefits of building scalable and resilient applications.

Uploaded by

np03cs4a230131
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

Distributed systems

and Cloud Computing

Lecture 3
The Actor Model
Why Actor Model?

Our CPUs are not getting any faster.

What’s happening is that we now have multiple cores on them.

If we want to take advantage of all this hardware we have available


now, we need a way to run our code concurrently.

Decades of untraceable bugs and developers’ depression have shown


that threads are not the way to go.

But fear not, there are great alternatives out there and today I want to
show you one of them: The actor model.
What is the Actor Model?
Properties of an actor

● Message: is a unit of communication between actors and it should


be immutable.
● Mailbox: is used to buffer messages, because the actor’s states are
not modified by other actors, thus they send messages to another
actor.
● Actor Reference: Each actor has an actor reference which is the
facade between actors, is freely shared among actors by message
passing.
● Dispatcher: is a component ensuring actors with non-empty
mailboxes eventually get run by a specific thread and that these
messages are handled serially.
What can an actor do?

● Create more actors.


● Send messages to other actors.
● Designate what to do with the next message.
Actors have mailboxes

It’s important to understand that, although multiple actors can run at the
same time, an actor will process a given message sequentially.
what happens when an actor receives a
message
Actor behavior and state

An Actor changes its State upon receiving an incoming message


How actors send
message and
handle
message?
Actor Messaging 14
Actor Messaging 15
What happens
when there is no
response?
No Response 17
Send Another Message 18
Still No Response 19
Ideal Situation 20
Alternate Plan 21
Timeout Cancelled 22
Timeout Expired 23
Supervisors
Supervisor actor creates worker actors 25
Worker actor has problem and notifies its 26

supervisor
Supervisor fixes problem 27
Supervisor actor delegates tasks to 28

worker actors
Worker actors perform tasks asynchronously 29
Actors and Scaling 30

● Supervisor adds more worker actors as the processing load increases


Actors and Scaling 31

● The supervisor sheds workers as the load decreases


Scaling Large Systems 32

● Actors exist within an actor system

● Actor system provides the protocol for messaging between actors

● It also manages actor activities by allocating the system resources


needed to support the actor environment.
Resources in a Computer System 33

● Every computer system has a set of processing cores, memory, disk


space, network interfaces, and so on

● When programs run, the work is handled by a thread of execution.

● With limited number of CPU cores and limited memory, there will
be limited number of threads available.

● The number of cores and the amount of memory determine how


much work or threads a computer system is capable of handling.

● This is similar to a room. Depending on the size of an office, more


workers will fit in the room if it is larger, which means it can handle
more work (threads).
How Actors Manage Requests 34

● An office example where workers


sit at desks to perform tasks only
when the desk has power
Requests Example 35

● One desk has power, so the


worker at that desk may work on
its assigned task
Requests Example 36

● Messages are sent to the office


and then routed to each worker
Requests Example 37

● The system swaps the power


between desks to allow an even
distribution of work
Traditional Threaded System 38

● When messages arrive faster


than the workers can perform
each task, then there is a
backlog of pending messages
that are either queued or
discarded
Asynchronous 39

● In an asynchronous
system, workers only
occupy desks when they
have something to do
Actor Clusters 40

● Actor systems may run in a cluster


Failure Detection and Recovery
41

● There are a number of strategies available both at the actor level and
at the actor system level.
● Actors that create other actors are supervisors, and for error handling
supervisors are notified when a worker hits a problem, and there are
four common recovery steps:
○ Ignore the error and let the worker resume processing

○ Restart the worker and perform a worker reset

○ Stop the worker

○ Escalate the problem to the supervising actor of the supervisor

● How a supervisor handles problems with a worker is not limited to


these four recovery options, but other strategies may also be used
when necessary.
Actors form hierarchies 42
Actors Watching Actors 43

● Sentinel actors watch actors on other nodes in the cluster


Actor Failure 44

● When a node fails, the sentinel actors are notified via an actor terminated
message
Akka
Framework
Akka

● Akka is a open-source library or a toolkit


● It is used to create concurrent, distributed and fault-tolerant
application
● It implements Actor Based Model
● Akka creates a layer between the actors and the underlying
system such that actors simply need to process messages
● The framework handles the creating and scheduling of
threads, receiving and dispatching messages, and handling
synchronization.
The Reactive Manifesto

● Akka adheres to the The Reactive Manifesto.


● Reactive applications aim at replacing traditional
multithreaded applications with an architecture that
satisfies one or more of the following requirements:
○ Event-driven.
○ Scalable.
○ Resilient.
○ Responsive.
● Event-driven.
○ Using Actors, one can write code that handles requests
asynchronously and employs non-blocking operations exclusively.
● Scalable.
○ In Akka, adding nodes without having to modify the code is possible,
thanks both to message passing and location transparency.
● Resilient.
○ Any application will encounter errors and fail at some point in time.
Akka provides fault tolerance strategies to facilitate a self-healing
system.
● Responsive.
○ Many of today’s high performance and rapid response applications
need to give quick feedback to the user and therefore need to react
to events in an extremely timely manner. Akka’s non-blocking,
message-based strategy helps achieve this.
Actor
● An actor is essentially nothing more than an object that receives messages
and takes actions to handle them. An actor is an entity which communicates to
other actor by message passing
● Actor has its own state and behavior.
● As in object-oriented programming everything is an object same like
everything is an actor in actor-based system.
● It is decoupled from the source of the message and it's only responsibility is to
properly recognize the type of message it has received and take action
accordingly.
● Upon receiving a message, an actor may take one or more of the following
actions:
○ Execute some operations itself (such as performing calculations, persisting data, calling an
external web service, and so on)
○ Forward the message, or a derived message, to another actor
○ Instantiate a new actor and forward the message to it
● Alternatively, the actor may choose to ignore the message entirely (i.e., it may
choose inaction) if it deems it appropriate to do so.
How to create an Actor?

● To implement an actor, extend the akka.actor.AbstractActor


class and implement the createReceive() method.
● An actor’s createReceive() method is invoked when a
message is sent to that actor.
● Its typical implementation is to identify the message type
and react accordingly
● If a message is not matched, it is logged in Akka event logs
● A catch-all matchAny() can be used to match any message.
Akka Actor class

public class ActorA extends AbstractActor {


@Override
public Receive createReceive() {
return receiveBuilder()
.match(MessageA.class, this::onMessageA)
.build();
}
private void onMessageA(MessageA msg) {
System.out.println("Actor A received : "+ msg.text + " from " +
getSender());
}
}
Akka ActorSystem

● The ActorSystem is a root actor in actors structure.


● An ActorSystem is a hierarchical group of actors which
share common configuration, e.g. dispatchers,
deployments, remote capabilities and addresses.
● It is also the entry point for creating or looking up actors.
● It is an abstract class which extends to ActorRefFactory
trait.
Akka Props

● Props is a configuration class used to create actors


● You can implement Props by importing akka.actor.Props
package.

public static void main(String[] args) {


ActorSystem system = ActorSystem.create();
ActorRef actorARef =
system.actorOf(Props.create(ActorA.class));
actorARef.tell(new MessageA("Hello!"),actorARef);
}
Akka Creating Child Actor

● Akka provides facility to create child actor.


● You can create child actor by using implicit context
reference.
● ActorSystem is used to create root-level or top-level
actor.

getContext().getSystem().actorOf(Props.create(ActorB.cla
ss));
Akka Actor life cycle

● Akka provides life cycle methods for Actor.


● There are following methods to which you can
override and provide specific implementation
accordingly.
○ preStart()
○ postStart()
○ preRestart(reason: Throwable, message: Option[Any])
○ postRestart(reason: Throwable))
Akka Actor Communication

● In Akka, actors communicate to each other by sending


and receiving messages.
○ Akka Actor Send Messages
○ Akka Actor Reply Messages
○ Akka Actor Forward Messages
Akka Actor Send Messages

● Akka provides two predefined methods tell() and ask()


for message exchange. An actor can send messages to
another Actor through these methods.
○ Receiver.tell(Message object, Sender);
○ Receiver.ask(Message object, Sender);
Akka Actor Reply Messages

● You can reply to a message by using sender() method


○ getSender().tell(Message object,getSelf())
Actor Forward Message

● You can forward a message from one actor to another.


● In this case, address/reference of an Actor is maintained even
though the message is going through a 'mediator'.
● It is helpful when writing actors that work as routers,
load-balancers, replicators etc.
○ target.forward(result, getContext());
Receiving messages

public Receive createReceive() {


return receiveBuilder()
.match(String.class,
s -> System.out.println(s)).build();
}
Stopping Actors

● you can stop Actors by invoking the stop() method of either


ActorContext or ActorSystem class
○ getContext().stop(child));
● ActorContext is used to stop child actor and ActorSystem is
used to stop top level Actor.
● Termination of the actor is performed asynchronously.
● There are some other methods available in Akka, which are
used to stop Actor. Some of which are PoisonPill, terminate() and
gracefulStop() are used to stop Actor.

You might also like