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

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 OpenCredo
 
Actor-based concurrency and Akka Fundamentals
Actor-based concurrency and Akka FundamentalsActor-based concurrency and Akka Fundamentals
Actor-based concurrency and Akka FundamentalsNgoc Dao
 
Actor model in .NET - Akka.NET
Actor model in .NET - Akka.NETActor model in .NET - Akka.NET
Actor model in .NET - Akka.NETKonrad Dusza
 
Ruby Interview Questions
Ruby Interview QuestionsRuby Interview Questions
Ruby Interview QuestionsSumanth krishna
 
C#: Understanding ConfigureAwait(false)
C#: Understanding ConfigureAwait(false)C#: Understanding ConfigureAwait(false)
C#: Understanding ConfigureAwait(false)Shuhei Eda
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooksMaulik Shah
 
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 AkkaNgoc Dao
 
Scal`a`ngular - Scala and Angular
Scal`a`ngular - Scala and AngularScal`a`ngular - Scala and Angular
Scal`a`ngular - Scala and AngularKnoldus Inc.
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced JavascriptDhruvin Shah
 
Advanced Reflection in Pharo
Advanced Reflection in PharoAdvanced Reflection in Pharo
Advanced Reflection in PharoMarcus Denker
 
Scope demystified - AngularJS
Scope demystified - AngularJSScope demystified - AngularJS
Scope demystified - AngularJSSumanth krishna
 
Xtend - better java with -less- noise
Xtend - better java with -less- noiseXtend - better java with -less- noise
Xtend - better java with -less- noiseNeeraj Bhusare
 
Actor Patterns and NATS - Boulder Meetup
Actor Patterns and NATS - Boulder MeetupActor Patterns and NATS - Boulder Meetup
Actor Patterns and NATS - Boulder MeetupApcera
 
Hello, React Hooks!
Hello, React Hooks!Hello, React Hooks!
Hello, React Hooks!Heejong Ahn
 

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

Asynchronous stream processing with Akka Streams
Asynchronous stream processing with Akka StreamsAsynchronous stream processing with Akka Streams
Asynchronous stream processing with Akka StreamsJohan Andrén
 
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 HelmanHakka Labs
 
Akka Streams and HTTP
Akka Streams and HTTPAkka Streams and HTTP
Akka Streams and HTTPRoland Kuhn
 
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 scenarioGioia Ballin
 
Recommendation at Netflix Scale
Recommendation at Netflix ScaleRecommendation at Netflix Scale
Recommendation at Netflix ScaleJustin Basilico
 
Akka in 100 slides or less
Akka in 100 slides or lessAkka in 100 slides or less
Akka in 100 slides or lessDerek Wyatt
 
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)Adam Kawa
 
(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 AWSAmazon Web Services
 
St Valentine Poetry
St Valentine PoetrySt Valentine Poetry
St Valentine Poetryisarevi
 
Presentazione Our Ideal Holiday Place
Presentazione Our Ideal Holiday Place  Presentazione Our Ideal Holiday Place
Presentazione Our Ideal Holiday Place isarevi
 
The Mocking Diañu
The Mocking Diañu   The Mocking Diañu
The Mocking Diañu isarevi
 
Hamburger
Hamburger   Hamburger
Hamburger 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

Akka Actors: an Introduction
Akka Actors: an IntroductionAkka Actors: an Introduction
Akka Actors: an IntroductionRoberto Casadei
 
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 HerokuSalesforce Developers
 
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 HoekRubiX BV
 
Akka lsug skills matter
Akka lsug skills matterAkka lsug skills matter
Akka lsug skills matterSkills Matter
 
Scaling Web Apps with Akka
Scaling Web Apps with AkkaScaling Web Apps with Akka
Scaling Web Apps with AkkaMaciej Matyjas
 
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.NetSören Stelzer
 
Nairobi JVM meetup : Introduction to akka
Nairobi JVM meetup : Introduction to akkaNairobi JVM meetup : Introduction to akka
Nairobi JVM meetup : Introduction to akkaAD_
 
Reactive programming with akka
Reactive programming with akkaReactive programming with akka
Reactive programming with akkaWebdesign Factory
 
Java util concurrent
Java util concurrentJava util concurrent
Java util concurrentRoger Xia
 
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 GroupRoy Russo
 
Akka london scala_user_group
Akka london scala_user_groupAkka london scala_user_group
Akka london scala_user_groupSkills Matter
 
GPars (Groovy Parallel Systems)
GPars (Groovy Parallel Systems)GPars (Groovy Parallel Systems)
GPars (Groovy Parallel Systems)Gagan Agrawal
 
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 AndroidFernando Cejas
 
Sagas Middleware Architecture
Sagas Middleware ArchitectureSagas Middleware Architecture
Sagas Middleware ArchitectureMateusz Bosek
 
Concurrency in Scala - the Akka way
Concurrency in Scala - the Akka wayConcurrency in Scala - the Akka way
Concurrency in Scala - the Akka wayYardena Meymann
 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in JavaRuben Inoto Soto
 
Hooks and Events in Drupal 8
Hooks and Events in Drupal 8Hooks and Events in Drupal 8
Hooks and Events in Drupal 8Nida Ismail Shah
 
Drilling the Async Library
Drilling the Async LibraryDrilling the Async Library
Drilling the Async LibraryKnoldus Inc.
 

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

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
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 TerraformAndrey Devyatkin
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
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 Processorsdebabhi2
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
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 connectorsNanddeep Nachan
 

Recently uploaded (20)

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
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
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
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
 
+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...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
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
 

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.