SlideShare a Scribd company logo
1 of 37
Download to read offline
Java/Scala Developer
何永琳
Introduction to
Actor Model & Akka
The Challenge
–The clock speed has
stopped growing since 2006


–The free lunch is over

–Moore’s Law still applies but
only the number of cores in a
single chip is increasing.

–The new reality: Amdahl's
Law.




                                   ref: http://en.wikipedia.org/wiki/Amdahl's_law
Concurrency and Parallelism
–Concurrency: A condition that exists when at least two threads are making
progress. A more generalized form of parallelism that can include time-slicing as
a form of virtual parallelism.


–Parallelism: A condition that arises when at least two threads are executing
simultaneously.


–Both of them are hard because of shared mutable state.
Issue: Shared Memory Concurrency
–Multithreaded Programs are hard to write and test
  – Non-deterministic
  – Data Race / Race Condition
  – Locks are hard to use
     – too many locks
     – too few locks
     – locks in wrong order

–Poor Performance.
  – False sharing: Cache Line Issue.
The solution
–A new high level programming model
  – easier to understand
  – deterministic
  – no shared/mutable state
  – fully utilize multi-core processors

–Possible Solutions:
  – Functional Programming - Everything is immutable.

    scala> List(1, 2, 3).par.map(_ + 2)
    res: List[Int] = List(3, 4, 5)


  – Actor Model - Keep mutable state internal and communicate with each other
    through asynchronous messages.
A Brief of the Actor Model
–Formalized in 1973 by Carl Hewitt and refined by Gul Agha in mid 80s.

–The first major adoption is done by Ericsson in mid 80s.

  – Invented Erlang and later open-sourced in 90s.

  – Built a distributed, concurrent, and fault-tolerant telcom system which has
    99.9999999% uptime
Actor Model
–Actors instead of Objects

–No shared state between actors.

–Asynchronous message passing.
Actor
–Lightweight object.

–Keep state internally

–Asynchronous and non-
blocking

–Messages are kept in mailbox
and processed in order.

–Massive scalable and lighting
fast because of the small call
stack.
Introduce Akka
–Founded by Jonas Boner and now part of Typesafe stack.

–Actor implementation on JVM.

–Java API and Scala API

–Support Remote Actor

–Modules: akka-camel, akka-spring, akka-zeromq
Define Actor

1. import akka.actor.UntypedActor;
2.  
3. public class Counter extends UntypedActor {
4.  
5.   private int count = 0;
6.  
7.   public void onReceive(Object message) throws Exception {
8.     if (message.equals("increase") {
9.       count += 1;
10.    } else if (message.equals("get") {
11.      getSender().tell(new Result(count));
12.    } else {
13.      unhandled(message);
14.    }
15.  }
16.}
Create And Send Message


1. // Create an Akka system
2. ActorSystem system = ActorSystem.create("MySystem");
3.  
4. // create a counter
5. final ActorRef counter =
6.     system.actorOf(new Props(Counter.class), "counter");
7.  
8. // send message to the counter
9. counter.tell("increase");
10.Future<Object> count = ask(counter, "get");
More on the Futures
1. // build a model for a EC site.
2. def doSearch(userId: String, keyword: String) {
3.  
4.   val sessionFuture = ask(sessionManager, GetSession(userId))
5.   val adFuture = ask(advertiser, GetAdvertisement)
6.   val resultFuture = ask(searcher, Search(keyword))
7.  
8.   val recommFuture = sessionFuture.map {
9.     session => ask(recommender,  Get(keyword, session))
10.  }
11. 
12.  val responseFuture = for {
13.    ad: Advertisement     <- adFuture
14.    result: SearchResult   <- resultFuture
15.    recomm: Recommendation <- recommFuture
16.  } yield new Model(ad, result, recomm)
17.  return responseFuture.get
18.}
Fault Tolerance in Akka

                     supervisor




worker      worker                worker   worker
Fault Tolerance in Akka

                     supervisor




worker      worker                worker   worker
Fault Tolerance in Akka

                     supervisor




worker      worker                  worker   worker




             •One-For-One restart strategy
             •One-For-All restart strategy
Fault Tolerance in Akka
                        supervisor




           supervisor           supervisor




worker      worker               worker      worker
Fault Tolerance in Akka
                        supervisor




           supervisor           supervisor




worker      worker               worker      worker
Fault Tolerance in Akka
                        supervisor




           supervisor           supervisor




worker      worker               worker      worker
Fault Tolerance in Akka
                        supervisor




           supervisor           supervisor




worker      worker               worker      worker
Fault Tolerance in Akka
                        supervisor




           supervisor           supervisor




worker      worker               worker      worker
Fault Tolerance in Akka
1. public class MySupervisor extends UntypedActor {
2.   // Restart the child if it throws ServiceUnavailable
3.   private static SupervisorStrategy strategy =
4.     new OneForOneStrategy(3, Duration.parse(“5 seconds”),
5.     new Function<Throwable, Directive>() {
6.       @Override
7.       public Directive apply(Throwable t) {
8.         if (t instanceof IOException) {
9.           return restart();
10.        } else {
11.          return escalate();
12.        }
13.      }
14.    });
15. 
16.  @Override
17.  public SupervisorStrategy supervisorStrategy() {
18.    return strategy;
19.  }
20.}
Remote Actor
–Actors are location transparent and distributable by design.

–All Actors can be remote actor through configuration without any code changes.

–Sending message to a remote Actor is as simple as sending message to local
Actor.

–Messages are serialized through java serialization, Protocol Buffer serializer or
custom serializer. The desired behavior is configurable in the config file.
Remote Actor
1. // define a remote address
2. Address addr =
3.   new Address("serializer", "MySystem", "host", 1234);
4.  
5. // initialize an actor on remote host programmatically.
6. ActorRef ref = system.actorOf(
7.   new Props(Counter.class)
8.     .withDeploy(
9.       new Deploy(new RemoteScope(addr)
10.    )
11.  )
12.);
Routing & Clustering
–Clustering support is still under construction and will be available in 2.1 release.

–A Router routes incoming messages to outbound actors.
  – RoundRobinRouter
  – RandomRouter
  – SmallestMailboxRouter
  – BroadcastRouter
  – ScatterGatherFirstCompletedRouter



 1. ActorRef router = system.actorOf(
 2.   new Props(ExampleActor.class)
 3.     .withRouter(new RoundRobinRouter(5))
 4. );
Performance




ref: http://letitcrash.com/post/17607272336/scalability-of-fork-join-pool
Use Cases
–Event driven messaging system

–Stock trend analysis and simulation.

–Rule based engine.

–Multiplayer online games.
case study -
twitter-like messaging service
Messaging Service.
–Publisher
  – keeps a list of reference to subscribers.
  – when it receives a message, it will forward the message to subscribers.


–Subscribers
  – stores received messages.
Protocol Classes

1. public class Message implements Serializable {
2.     public final String sender;
3.     public final String message;
4.     public final DateTime createDate;
5.     //skipped...
6. }
7. public class GetMessages implements Serializable {
8.     public final DateTime since;
9.     //skipped...
10.}
11.public class Subscribe implements Serializable {
12.    public final ActorRef subscriber;
13.    //skipped...
14.}
The Actor
1. public class PubSubscriber extends UntypedActor {
2.   private final String name;
3.   private final List<Message> received = Lists.newArrayList();
4.   private final Set<ActorRef> subscribers = Sets.newHashSet();
5.   public PubSubscriber(String name) {
6.     this.name = name;
7.   }
8.   public void onReceive(Object message) {
9.     if (message instanceof Subscribe) {
10.      subscribers.add(((Subscribe) message).subscriber);
11.   } else if (message instanceof Message) {
12.      Message msg = (Message) message;
13.      // if sender is self, forward the message to subscriber.
14.       if (Objects.equal(msg.sender, name)) {
15.        for (ActorRef subscriber: subscribers) {
16.          subscriber.tell(msg);
17.        }
18.      } else {
19.        received.add((Message) message);
20.      }
The Actor
21.}   else if (message instanceof GetMessages) {
22.      final DateTime since = ((GetMessages) message).since;
23.      Iterable<Message> ret = Iterables.filter(received,
24.          new Predicate<Message>() {
25.          @Override
26.          public boolean apply(@Nullable Message message) {
27.            return message.createDate.isAfter(since);
28.          }
29.        });
30.        getSender().tell(ret);
31.      } else {
32.        unhandled(message);
33.      }
34.    }
35.}
External Interface
–Akka-Camel
1. class JettyAdapter extends Consumer with ActorLogging {
2.  
3.   def endpointUri = "jetty:http://localhost:8080/"
4.  
5.   override def receive = {
6.     case CamelMessage(body, headers) => {
7.       headers.get("op") match {
8.         case Some("msg")   => handleMessagingOp(headers)
9.         case Some("get")   => handleGetOp(headers)
10.        case op            => handleUnsupportedOp(op)
11.      }
12.    }
13.  }
External Interface
14.private def handleMessagingOp(headers: Map[String, Any]) {
15.  val tweetOption = for(
16.   name  <- headers.get("name");
17.    msg  <- headers.get("msg")
18.  ) yield new Message(name.toString, msg.toString, DateTime.now)
19. 
20.  tweetOption match {
21.    case Some(message) => {
22.      findOrCreateActorRef(msg).forward(message)
23.   }
24.   case None => {
25.     sender ! "Unable to perform Action."
26.   }
27.}}
28.private def findOrCreateActorRef(name: String): ActorRef = {
29.  val pubsub = context.actorFor(name)
30.  if (pubsub.isTerminated) {
31.    context.actorOf(Props(new PubSubscriber(name)), name = name)
32.  } else { pubsub }
33.}
Handle Server Shutdown
–When server stops, we need to persist state to external storage.
  – actors’ state
  – unprocessed messages in mail boxes.


–For actor’s state, you can implement preStart and postStop method to persiste
state to external storage.

–For unprocessed message, Akka provides durable mail box backed by local file
system.
Going Remote.
–There is no code changes to the PubSubscriber or protocol classes.
  – The protocol classes are serializable and immutable already.
  – The subscriber reference, the ActorRef, is remote ready too.


–The only missing piece is the one connects the actors. We need to rewrite the
findOrCreateActor() method.
   – In Akka 2.1 release, it will provide a new cluster module to solve this issue.
Q&A
yunglin@gmail.com
twitter: @yunglinho

More Related Content

What's hot

Actor-based concurrency and Akka Fundamentals
Actor-based concurrency and Akka FundamentalsActor-based concurrency and Akka Fundamentals
Actor-based concurrency and Akka Fundamentals
Ngoc Dao
 

What's hot (20)

Spring Boot Microservices vs Akka Actor Cluster
Spring Boot Microservices vs Akka Actor Cluster Spring Boot Microservices vs Akka Actor Cluster
Spring Boot Microservices vs Akka Actor Cluster
 
Actor-based concurrency and Akka Fundamentals
Actor-based concurrency and Akka FundamentalsActor-based concurrency and Akka Fundamentals
Actor-based concurrency and Akka Fundamentals
 
Akka (BeJUG)
Akka (BeJUG)Akka (BeJUG)
Akka (BeJUG)
 
Actor model in .NET - Akka.NET
Actor model in .NET - Akka.NETActor model in .NET - Akka.NET
Actor model in .NET - Akka.NET
 
Actor Model & Reactive Manifesto
Actor Model & Reactive ManifestoActor Model & Reactive Manifesto
Actor Model & Reactive Manifesto
 
Ruby Interview Questions
Ruby Interview QuestionsRuby Interview Questions
Ruby Interview Questions
 
C#: Understanding ConfigureAwait(false)
C#: Understanding ConfigureAwait(false)C#: Understanding ConfigureAwait(false)
C#: Understanding ConfigureAwait(false)
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooks
 
Model with actors and implement with Akka
Model with actors and implement with AkkaModel with actors and implement with Akka
Model with actors and implement with Akka
 
Scal`a`ngular - Scala and Angular
Scal`a`ngular - Scala and AngularScal`a`ngular - Scala and Angular
Scal`a`ngular - Scala and Angular
 
React hooks
React hooksReact hooks
React hooks
 
Lecture1
Lecture1Lecture1
Lecture1
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
Advanced Reflection in Pharo
Advanced Reflection in PharoAdvanced Reflection in Pharo
Advanced Reflection in Pharo
 
Scope demystified - AngularJS
Scope demystified - AngularJSScope demystified - AngularJS
Scope demystified - AngularJS
 
Xtend - better java with -less- noise
Xtend - better java with -less- noiseXtend - better java with -less- noise
Xtend - better java with -less- noise
 
Actor Patterns and NATS - Boulder Meetup
Actor Patterns and NATS - Boulder MeetupActor Patterns and NATS - Boulder Meetup
Actor Patterns and NATS - Boulder Meetup
 
Redux
ReduxRedux
Redux
 
Hello, React Hooks!
Hello, React Hooks!Hello, React Hooks!
Hello, React Hooks!
 
Driver
DriverDriver
Driver
 

Viewers also liked

(BDT317) Building A Data Lake On AWS
(BDT317) Building A Data Lake On AWS(BDT317) Building A Data Lake On AWS
(BDT317) Building A Data Lake On AWS
Amazon Web Services
 
St Valentine Poetry
St Valentine PoetrySt Valentine Poetry
St Valentine Poetry
isarevi
 
Presentazione Our Ideal Holiday Place
Presentazione Our Ideal Holiday Place  Presentazione Our Ideal Holiday Place
Presentazione Our Ideal Holiday Place
isarevi
 

Viewers also liked (20)

Go lang - What is that thing?
Go lang - What is that thing?Go lang - What is that thing?
Go lang - What is that thing?
 
Go Lang Tutorial
Go Lang TutorialGo Lang Tutorial
Go Lang Tutorial
 
Asynchronous stream processing with Akka Streams
Asynchronous stream processing with Akka StreamsAsynchronous stream processing with Akka Streams
Asynchronous stream processing with Akka Streams
 
Mongo db - How we use Go and MongoDB by Sam Helman
Mongo db - How we use Go and MongoDB by Sam HelmanMongo db - How we use Go and MongoDB by Sam Helman
Mongo db - How we use Go and MongoDB by Sam Helman
 
H20: A platform for big math
H20: A platform for big math H20: A platform for big math
H20: A platform for big math
 
Akka Fundamentals
Akka FundamentalsAkka Fundamentals
Akka Fundamentals
 
Akka Streams and HTTP
Akka Streams and HTTPAkka Streams and HTTP
Akka Streams and HTTP
 
A dive into akka streams: from the basics to a real-world scenario
A dive into akka streams: from the basics to a real-world scenarioA dive into akka streams: from the basics to a real-world scenario
A dive into akka streams: from the basics to a real-world scenario
 
Recommendation at Netflix Scale
Recommendation at Netflix ScaleRecommendation at Netflix Scale
Recommendation at Netflix Scale
 
Akka in 100 slides or less
Akka in 100 slides or lessAkka in 100 slides or less
Akka in 100 slides or less
 
Hadoop Operations Powered By ... Hadoop (Hadoop Summit 2014 Amsterdam)
Hadoop Operations Powered By ... Hadoop (Hadoop Summit 2014 Amsterdam)Hadoop Operations Powered By ... Hadoop (Hadoop Summit 2014 Amsterdam)
Hadoop Operations Powered By ... Hadoop (Hadoop Summit 2014 Amsterdam)
 
Introducing Akka
Introducing AkkaIntroducing Akka
Introducing Akka
 
(BDT317) Building A Data Lake On AWS
(BDT317) Building A Data Lake On AWS(BDT317) Building A Data Lake On AWS
(BDT317) Building A Data Lake On AWS
 
St Valentine Poetry
St Valentine PoetrySt Valentine Poetry
St Valentine Poetry
 
физминутка
физминуткафизминутка
физминутка
 
Brown powerpoint
Brown powerpointBrown powerpoint
Brown powerpoint
 
Yaiza I
Yaiza IYaiza I
Yaiza I
 
Presentazione Our Ideal Holiday Place
Presentazione Our Ideal Holiday Place  Presentazione Our Ideal Holiday Place
Presentazione Our Ideal Holiday Place
 
The Mocking Diañu
The Mocking Diañu   The Mocking Diañu
The Mocking Diañu
 
Hamburger
Hamburger   Hamburger
Hamburger
 

Similar to Introduction to Actor Model and Akka

Build Cloud Applications with Akka and Heroku
Build Cloud Applications with Akka and HerokuBuild Cloud Applications with Akka and Heroku
Build Cloud Applications with Akka and Heroku
Salesforce Developers
 
Scaling Web Apps with Akka
Scaling Web Apps with AkkaScaling Web Apps with Akka
Scaling Web Apps with Akka
Maciej Matyjas
 
Akka london scala_user_group
Akka london scala_user_groupAkka london scala_user_group
Akka london scala_user_group
Skills Matter
 
Concurrency in Scala - the Akka way
Concurrency in Scala - the Akka wayConcurrency in Scala - the Akka way
Concurrency in Scala - the Akka way
Yardena Meymann
 

Similar to Introduction to Actor Model and Akka (20)

Scale up your thinking
Scale up your thinkingScale up your thinking
Scale up your thinking
 
Akka Actors: an Introduction
Akka Actors: an IntroductionAkka Actors: an Introduction
Akka Actors: an Introduction
 
G pars
G parsG pars
G pars
 
Build Cloud Applications with Akka and Heroku
Build Cloud Applications with Akka and HerokuBuild Cloud Applications with Akka and Heroku
Build Cloud Applications with Akka and Heroku
 
Reactive Streams - László van den Hoek
Reactive Streams - László van den HoekReactive Streams - László van den Hoek
Reactive Streams - László van den Hoek
 
Akka lsug skills matter
Akka lsug skills matterAkka lsug skills matter
Akka lsug skills matter
 
Scaling Web Apps with Akka
Scaling Web Apps with AkkaScaling Web Apps with Akka
Scaling Web Apps with Akka
 
Reactive Programming in .Net - actorbased computing with Akka.Net
Reactive Programming in .Net - actorbased computing with Akka.NetReactive Programming in .Net - actorbased computing with Akka.Net
Reactive Programming in .Net - actorbased computing with Akka.Net
 
Nairobi JVM meetup : Introduction to akka
Nairobi JVM meetup : Introduction to akkaNairobi JVM meetup : Introduction to akka
Nairobi JVM meetup : Introduction to akka
 
Reactive programming with akka
Reactive programming with akkaReactive programming with akka
Reactive programming with akka
 
Java util concurrent
Java util concurrentJava util concurrent
Java util concurrent
 
Introduction to Akka - Atlanta Java Users Group
Introduction to Akka - Atlanta Java Users GroupIntroduction to Akka - Atlanta Java Users Group
Introduction to Akka - Atlanta Java Users Group
 
Akka london scala_user_group
Akka london scala_user_groupAkka london scala_user_group
Akka london scala_user_group
 
GPars (Groovy Parallel Systems)
GPars (Groovy Parallel Systems)GPars (Groovy Parallel Systems)
GPars (Groovy Parallel Systems)
 
The Mayans Lost Guide to RxJava on Android
The Mayans Lost Guide to RxJava on AndroidThe Mayans Lost Guide to RxJava on Android
The Mayans Lost Guide to RxJava on Android
 
Sagas Middleware Architecture
Sagas Middleware ArchitectureSagas Middleware Architecture
Sagas Middleware Architecture
 
Concurrency in Scala - the Akka way
Concurrency in Scala - the Akka wayConcurrency in Scala - the Akka way
Concurrency in Scala - the Akka way
 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in Java
 
Hooks and Events in Drupal 8
Hooks and Events in Drupal 8Hooks and Events in Drupal 8
Hooks and Events in Drupal 8
 
Drilling the Async Library
Drilling the Async LibraryDrilling the Async Library
Drilling the Async Library
 

Recently uploaded

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 

Recently uploaded (20)

[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 

Introduction to Actor Model and Akka

  • 3. The Challenge –The clock speed has stopped growing since 2006 –The free lunch is over –Moore’s Law still applies but only the number of cores in a single chip is increasing. –The new reality: Amdahl's Law. ref: http://en.wikipedia.org/wiki/Amdahl's_law
  • 4. Concurrency and Parallelism –Concurrency: A condition that exists when at least two threads are making progress. A more generalized form of parallelism that can include time-slicing as a form of virtual parallelism. –Parallelism: A condition that arises when at least two threads are executing simultaneously. –Both of them are hard because of shared mutable state.
  • 5. Issue: Shared Memory Concurrency –Multithreaded Programs are hard to write and test – Non-deterministic – Data Race / Race Condition – Locks are hard to use – too many locks – too few locks – locks in wrong order –Poor Performance. – False sharing: Cache Line Issue.
  • 6. The solution –A new high level programming model – easier to understand – deterministic – no shared/mutable state – fully utilize multi-core processors –Possible Solutions: – Functional Programming - Everything is immutable. scala> List(1, 2, 3).par.map(_ + 2) res: List[Int] = List(3, 4, 5) – Actor Model - Keep mutable state internal and communicate with each other through asynchronous messages.
  • 7. A Brief of the Actor Model –Formalized in 1973 by Carl Hewitt and refined by Gul Agha in mid 80s. –The first major adoption is done by Ericsson in mid 80s. – Invented Erlang and later open-sourced in 90s. – Built a distributed, concurrent, and fault-tolerant telcom system which has 99.9999999% uptime
  • 8. Actor Model –Actors instead of Objects –No shared state between actors. –Asynchronous message passing.
  • 9. Actor –Lightweight object. –Keep state internally –Asynchronous and non- blocking –Messages are kept in mailbox and processed in order. –Massive scalable and lighting fast because of the small call stack.
  • 10. Introduce Akka –Founded by Jonas Boner and now part of Typesafe stack. –Actor implementation on JVM. –Java API and Scala API –Support Remote Actor –Modules: akka-camel, akka-spring, akka-zeromq
  • 11. Define Actor 1. import akka.actor.UntypedActor; 2.   3. public class Counter extends UntypedActor { 4.   5.   private int count = 0; 6.   7.   public void onReceive(Object message) throws Exception { 8.     if (message.equals("increase") { 9.       count += 1; 10.    } else if (message.equals("get") { 11.      getSender().tell(new Result(count)); 12.    } else { 13.      unhandled(message); 14.    } 15.  } 16.}
  • 12. Create And Send Message 1. // Create an Akka system 2. ActorSystem system = ActorSystem.create("MySystem"); 3.   4. // create a counter 5. final ActorRef counter = 6.     system.actorOf(new Props(Counter.class), "counter"); 7.   8. // send message to the counter 9. counter.tell("increase"); 10.Future<Object> count = ask(counter, "get");
  • 13. More on the Futures 1. // build a model for a EC site. 2. def doSearch(userId: String, keyword: String) { 3.   4.   val sessionFuture = ask(sessionManager, GetSession(userId)) 5.   val adFuture = ask(advertiser, GetAdvertisement) 6.   val resultFuture = ask(searcher, Search(keyword)) 7.   8.   val recommFuture = sessionFuture.map { 9.     session => ask(recommender,  Get(keyword, session)) 10.  } 11.  12.  val responseFuture = for { 13.    ad: Advertisement     <- adFuture 14.    result: SearchResult   <- resultFuture 15.    recomm: Recommendation <- recommFuture 16.  } yield new Model(ad, result, recomm) 17.  return responseFuture.get 18.}
  • 14. Fault Tolerance in Akka supervisor worker worker worker worker
  • 15. Fault Tolerance in Akka supervisor worker worker worker worker
  • 16. Fault Tolerance in Akka supervisor worker worker worker worker •One-For-One restart strategy •One-For-All restart strategy
  • 17. Fault Tolerance in Akka supervisor supervisor supervisor worker worker worker worker
  • 18. Fault Tolerance in Akka supervisor supervisor supervisor worker worker worker worker
  • 19. Fault Tolerance in Akka supervisor supervisor supervisor worker worker worker worker
  • 20. Fault Tolerance in Akka supervisor supervisor supervisor worker worker worker worker
  • 21. Fault Tolerance in Akka supervisor supervisor supervisor worker worker worker worker
  • 22. Fault Tolerance in Akka 1. public class MySupervisor extends UntypedActor { 2.   // Restart the child if it throws ServiceUnavailable 3.   private static SupervisorStrategy strategy = 4.     new OneForOneStrategy(3, Duration.parse(“5 seconds”), 5.     new Function<Throwable, Directive>() { 6.       @Override 7.       public Directive apply(Throwable t) { 8.         if (t instanceof IOException) { 9.           return restart(); 10.        } else { 11.          return escalate(); 12.        } 13.      } 14.    }); 15.  16.  @Override 17.  public SupervisorStrategy supervisorStrategy() { 18.    return strategy; 19.  } 20.}
  • 23. Remote Actor –Actors are location transparent and distributable by design. –All Actors can be remote actor through configuration without any code changes. –Sending message to a remote Actor is as simple as sending message to local Actor. –Messages are serialized through java serialization, Protocol Buffer serializer or custom serializer. The desired behavior is configurable in the config file.
  • 24. Remote Actor 1. // define a remote address 2. Address addr = 3.   new Address("serializer", "MySystem", "host", 1234); 4.   5. // initialize an actor on remote host programmatically. 6. ActorRef ref = system.actorOf( 7.   new Props(Counter.class) 8.     .withDeploy( 9.       new Deploy(new RemoteScope(addr) 10.    ) 11.  ) 12.);
  • 25. Routing & Clustering –Clustering support is still under construction and will be available in 2.1 release. –A Router routes incoming messages to outbound actors. – RoundRobinRouter – RandomRouter – SmallestMailboxRouter – BroadcastRouter – ScatterGatherFirstCompletedRouter 1. ActorRef router = system.actorOf( 2.   new Props(ExampleActor.class) 3.     .withRouter(new RoundRobinRouter(5)) 4. );
  • 27. Use Cases –Event driven messaging system –Stock trend analysis and simulation. –Rule based engine. –Multiplayer online games.
  • 28. case study - twitter-like messaging service
  • 29. Messaging Service. –Publisher – keeps a list of reference to subscribers. – when it receives a message, it will forward the message to subscribers. –Subscribers – stores received messages.
  • 30. Protocol Classes 1. public class Message implements Serializable { 2.     public final String sender; 3.     public final String message; 4.     public final DateTime createDate; 5.     //skipped... 6. } 7. public class GetMessages implements Serializable { 8.     public final DateTime since; 9.     //skipped... 10.} 11.public class Subscribe implements Serializable { 12.    public final ActorRef subscriber; 13.    //skipped... 14.}
  • 31. The Actor 1. public class PubSubscriber extends UntypedActor { 2.   private final String name; 3.   private final List<Message> received = Lists.newArrayList(); 4.   private final Set<ActorRef> subscribers = Sets.newHashSet(); 5.   public PubSubscriber(String name) { 6.     this.name = name; 7.   } 8.   public void onReceive(Object message) { 9.     if (message instanceof Subscribe) { 10.      subscribers.add(((Subscribe) message).subscriber); 11.   } else if (message instanceof Message) { 12.      Message msg = (Message) message; 13.      // if sender is self, forward the message to subscriber. 14.    if (Objects.equal(msg.sender, name)) { 15.        for (ActorRef subscriber: subscribers) { 16.          subscriber.tell(msg); 17.        } 18.      } else { 19.        received.add((Message) message); 20.      }
  • 32. The Actor 21.} else if (message instanceof GetMessages) { 22.    final DateTime since = ((GetMessages) message).since; 23.    Iterable<Message> ret = Iterables.filter(received, 24.        new Predicate<Message>() { 25.        @Override 26.        public boolean apply(@Nullable Message message) { 27.          return message.createDate.isAfter(since); 28.        } 29.      }); 30.      getSender().tell(ret); 31.    } else { 32.      unhandled(message); 33.    } 34.  } 35.}
  • 33. External Interface –Akka-Camel 1. class JettyAdapter extends Consumer with ActorLogging { 2.   3.   def endpointUri = "jetty:http://localhost:8080/" 4.   5.   override def receive = { 6.     case CamelMessage(body, headers) => { 7.       headers.get("op") match { 8.         case Some("msg") => handleMessagingOp(headers) 9.         case Some("get")   => handleGetOp(headers) 10.        case op            => handleUnsupportedOp(op) 11.      } 12.    } 13.  }
  • 34. External Interface 14.private def handleMessagingOp(headers: Map[String, Any]) { 15.  val tweetOption = for( 16.   name  <- headers.get("name"); 17.    msg  <- headers.get("msg") 18.  ) yield new Message(name.toString, msg.toString, DateTime.now) 19.  20.  tweetOption match { 21.    case Some(message) => { 22.      findOrCreateActorRef(msg).forward(message) 23.   } 24.   case None => { 25.     sender ! "Unable to perform Action." 26.   } 27.}} 28.private def findOrCreateActorRef(name: String): ActorRef = { 29.  val pubsub = context.actorFor(name) 30.  if (pubsub.isTerminated) { 31.    context.actorOf(Props(new PubSubscriber(name)), name = name) 32.  } else { pubsub } 33.}
  • 35. Handle Server Shutdown –When server stops, we need to persist state to external storage. – actors’ state – unprocessed messages in mail boxes. –For actor’s state, you can implement preStart and postStop method to persiste state to external storage. –For unprocessed message, Akka provides durable mail box backed by local file system.
  • 36. Going Remote. –There is no code changes to the PubSubscriber or protocol classes. – The protocol classes are serializable and immutable already. – The subscriber reference, the ActorRef, is remote ready too. –The only missing piece is the one connects the actors. We need to rewrite the findOrCreateActor() method. – In Akka 2.1 release, it will provide a new cluster module to solve this issue.