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

AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetEnjoy Anytime
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 

Recently uploaded (20)

AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 

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.