Actor Model & Akka

Source: Internet
Author: User
Tags file size visibility
Actor Model & AKKA Actor Model Actor Model in AKKA application of Akka in Pea pod Actor Model

The Actor model is a different way of modeling concurrent processes.
actor is a free-running activity that can receive messages, process messages, and send responses
designed primarily to support asynchronous and efficient messaging mechanisms

1.OOP: is a variable drive, each error is mutable, then we need to properly deal with visibility and competition conditions

2. Functional programming: Emphasizing immutability

3. When programming a role-based model, you tend to adopt a different design approach than normal object-oriented programming:
(1) Divide the problem into several computable asynchronous tasks in the city and assign them a different role.
(2) Each role is responsible for performing only the part of the task assigned to itself. This allows us to limit any mutable state to one of the many roles.

Actor model Features:
actor itself single thread
communication between different actors by passing an immutable message

1.Actor Single threaded: There are no issues related to visibility and race conditions, object state in OOP is encapsulated in objects, only instance methods can manipulate object state, and different threads may be called simultaneously, causing concurrency problems.
only one actor is allowed to manipulate the object state, that is, to isolate

the mutable state 2.Actor and Thread decoupling:
(1) When a pending message is received or a task is to be run, the role can be assigned to an available thread to execute
(2) An actor only one thread is active
(3) This ensures concurrency between multiple actors and eliminates competition between individual roles

Actor model life cycle

Create: An actor can either be started or be terminated after it is created
: Once started, the actor is ready to accept message
activity: When the actor is active, it is not processing the message or waiting for a new message to arrive
Stop: Once stopped, the character will not be receiving any messages.

For the entire life cycle, the time consuming to wait and process messages depends on the application they are in. The Actor model in AKKA AKKA is a concurrent processing framework that uses the Actor model and STM (software Transactional Memory) to enhance the idle sector, providing a better concurrency processing platform and high scalability.

Akka Features: Simpler scalability, high fault tolerance, concurrency control and remote control with actor

Akka Concrete Implementation

Create Actor:akka to create an actor in a controlled manner

Import Akka.actor.UntypedActor;

/**
 * Created by DELL on 2015/5/11.
 *

///Inherit Untypedactor and implement OnReceive method to receive the message public
class Hollywoodactor extends Untypedactor {

    private Final String name;

    Actor can receive some parameters public
    hollywoodactor (final String thename) {name=thename;}

    Used to receive the message public
    void OnReceive (final Object role) {
        if (role instanceof String)
            System.out.println ( String.Format ("%s playing%s", Name,role));
        else
            System.out.println (name + "plays no" +role);
    }
}

Send and Receive Messages

Any type of message can be sent, and the message sent must be immutable Sendoneway: non-blocking sendrequestreply (bidirectional message interaction mode): The calling thread will be blocked until the other party has received the corresponding or reached the time-out

Multi-Actors collaboration

Sizecontroller: By receiving a message to record the directory that needs to be scanned, to save the current value of the directory size, and to provide Fileprocessor with the directory fileprocessor that needs to be scanned: used to traverse files/directories in a given directory. is responsible for traversing the given directory and returning the size of all files under that directory and the names of all its subdirectories.

Import Akka.actor.Actor;
Import Akka.actor.ActorRef;
Import Akka.actor.UntypedActor;

Import Akka.actor.UntypedActorFactory;
Import Java.io.File;
Import java.util.ArrayList;


Import java.util.List; public class Concurrentfilesizewakka {//fileprocessor adds itself to the Sizecollector mailbox by requestafile message//sizecollector the message as Returns the Requestafile as the requested reply to Requestafile class Requestafile {}//File size information class FileSize {public final lon

        G size;

    Public FileSize (final long FileSize) {size = FileSize;} 

        The//filetoprocess message holds the subdirectory name that needs to be facilitated//is returned by Sizecollector as a reply to the Requestafile request to Requestafile class Filetoprocess {

        Public final String FileName;

    Public filetoprocess (final String name) {fileName = name;} } class Sizecollector extends Untypedactor {//directory to be accessed private final list<string> Toprocessfilena
        Mes = new arraylist<string> (); Free fileprocessor private Final list<actorref> IdlefileproCessors = new arraylist<actorref> ();
        Private long pendingnumberoffilestovisit = 0L;
        Private long totalsize = 0L;

        Private Long start = System.nanotime ();
                public void sendafiletoprocess () {if (!toprocessfilenames.isempty () &&!idlefileprocessors.isempty ()) Idlefileprocessors.remove (0). Sendoneway (New filetoprocess (Toprocessfilenames.remo
        ve (0))); The public void OnReceive (final Object message) {//indicates that there is a wait if (message instanceof Requestafil
                e) {Idlefileprocessors.add (GetContext (). Getsender (). get ());
            Sendafiletoprocess (); }//Receive and send messages//When you need to pick an idle processor to perform a statistical task, collector sends a message to the idle Fileprocessor//When a subdirectory is found in the traversal process , processor will notify the discovery to collector if (message instanceof filetoprocess) with this type of message {Toprocessfilenames.add (((filetoprocess) (message)). FileName);
                Pendingnumberoffilestovisit + = 1;
            Sendafiletoprocess ();
                if (message instanceof FileSize) {totalsize + = ((FileSize) (message)). Size;
                Pendingnumberoffilestovisit-= 1;
                    if (Pendingnumberoffilestovisit = = 0) {Long end = System.nanotime ();
                    SYSTEM.OUT.PRINTLN ("Total size is" + totalsize);
                    System.out.println ("Time Taken is" + (End-start)/1.0e9);
                Actors.registry (). ShutdownAll ();
        }}}}//class Fileprocessor extends untypedactor{//straight Sizecollector reference

        Private final Actorref Sizecollector;

        Public Fileprocessor (Final actorref thesizecontroller) {sizecollector = Thesizecontroller;}

        Each time the actor starts, it calls//wants Sizecollector to register @Override public void Prestart () {registertogetfile ();} Send Requestafile to express yourselfWaiting for public void Registertogetfile () {Sizecollector.sendoneway (New Requestafile (), GetContext ()); }//receives the message and processes public void OnReceive (final Object message) {filetoprocess filetoprocess = (
            filetoprocess) message;
            Final file File = new file (filetoprocess.filename);
            Long size = 0L;
            if (File.isfile ()) {size = File.length ();

                }else {file[] children = file.listfiles ();
                            if (children! = null) for (File Child:children) if (Child.isfile ())
                        Size + = Child.length ();
            else Sizecollector.sendoneway (New filetoprocess (Child.getpath ()));//Discovery is directory}

            Send Message Sizecollector.sendoneway (new FileSize (size));
        After the processing is finished, it indicates that he is waiting for the state registertogetfile (); }} public static void main (final string[] args) {final Actorref sizecollector = actors.actorof (sizecollector.clas
        s). Start ();
        Sizecollector.sendoneway (New Filetoprocess (Args[0]));  for (int i = 0; i <, i++) actors.actorof (new Untypedactorfactory () {public untypedactor
                Create () {return new fileprocessor (Sizecollector);
    }}). Start ();
 }



}
Pea pod Real-time response platform

Http://www.csdn.net/article/2014-11-21/2822770-wandoujia-Typesafe-Akka

Pea pod Real-time response platform tens of millions of mobile device linking system to better service anytime, anywhere with a real-time responsive platform Create a persistent connection channel and connect each device to our rear retransmitting. The backend continuously receives a large number of events from these devices and makes immediate response even to the "morphing" of the initiative. Using Akka

Overall: Each Actor responds to events or changes received, changes state, and then transmits new events or changes, while parallel behavior is the overall performance of a large number of Actors individual behaviors. 1. The connection layer maintains a persistent connection for each device. 2. Status layer: The status of each device is aligned by the Actor of the status layer to maintain the status of each connected device. 3.Distributed region and distributed mediator are the interface of the business logic (1) region accesses each status actor (2) according to the ID mediator: All events and messages are posted to mediator and eventually swapped Real-time event stream into Rxscala 4. The business layer simply subscribes to this event flow. Through the above architecture, different devices can share and query status, push events and messages in two directions, get real-time notifications, and actually implement a connection between all devices. Advantage Analysis: 1. Consistent clusters: Because the Actor pattern is the best granularity for both distributed and parallel computing, it's easy to switch from a single server to a cluster to deploy the same functionality, and Akka itself is a great level of scale, Online balance adjustment and online upgrade capabilities of the cluster platform. 2. Performance: For our application scenario, the performance so far is good enough. The cluster we are running now maintains more than 1 million persistent connections with 4 nodes, about 250,000 per node. The other 3 state nodes in the cluster handle more than 50,000 device heartbeats per second, plus 20,000 status requests per second. Based on our performance tests and estimates, the capabilities of the cluster are approximately: Each connection node can easily handle more than 1 million long connections, and each state node can process 15,000 status requests. We anticipate that as more nodes are gradually added to the cluster, we can reach tens or even hundreds of millions of of long connections in the near future, and the number of messages processed per second can reach hundreds of thousands of.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.