Introducing         Jonas Bonér          CTO Typesafe
Introducing
Introducing                Akka (Áhkká)  The name comes from the goddess in the Sami  (native swedes) mythology that repre...
Introducing
VisionSimpler     Concurrency     Scalability     Fault-tolerance
Vision...with a single unified     Programming Model     Managed Runtime     Open Source Distribution
Manage System Overload
Scale UP & Scale OUT
Program at a Higher Level
Program at a Higher Level
Program at a Higher Level• Never think in terms of shared state, state   visibility, threads, locks, concurrent collection...
Program at a Higher Level• Never think in terms of shared state, state   visibility, threads, locks, concurrent collection...
Program at a Higher Level• Never think in terms of shared state, state   visibility, threads, locks, concurrent collection...
Program at a Higher Level• Never think in terms of shared state, state   visibility, threads, locks, concurrent collection...
Distributable by Design
Distributable by Design
Distributable by Design• Actors are location transparent & distributable by design
Distributable by Design• Actors are location transparent & distributable by design• Scale UP and OUT for free as part of t...
Distributable by Design• Actors are location transparent & distributable by design• Scale UP and OUT for free as part of t...
Distributable by Design• Actors are location transparent & distributable by design• Scale UP and OUT for free as part of t...
Distributable by Design• Actors are location transparent & distributable by design• Scale UP and OUT for free as part of t...
Distributable by Design• Actors are location transparent & distributable by design• Scale UP and OUT for free as part of t...
Distributable by Design• Actors are location transparent & distributable by design• Scale UP and OUT for free as part of t...
Selection of Akka Production Users
Howcan we achieve this?
Howcan we achieve this?
Let’s use Actors     Howcan we achieve this?
What is an Actor?
What is an Actor?
What is an Actor?• Akkas unit of code organization is called an Actor
What is an Actor?• Akkas unit of code organization is called an Actor• Actors helps you create concurrent, scalable and   ...
What is an Actor?• Akkas unit of code organization is called an Actor• Actors helps you create concurrent, scalable and   ...
What is an Actor?• Akkas unit of code organization is called an Actor• Actors helps you create concurrent, scalable and   ...
Actors can be seen asVirtual Machines (nodes)  in Cloud Computing
Encapsulatedand decoupled black boxes...
Encapsulatedand decoupled black boxes...
...that manages their own   memory and behavior
...that manages their own   memory and behavior
Communicateswith asynchronous   non-blocking     messages
Communicateswith asynchronous   non-blocking     messages
Elastic - grow andshrink on demand
Elastic - grow andshrink on demand
Elastic - grow andshrink on demand
Elastic - grow andshrink on demand
Hot deploy - changebehavior at runtime
Hot deploy - changebehavior at runtime
Now - if we replace             with                    ActorEVERYTHING will STILL HOLD for both  LOCAL and DISTRIBUTED Ac...
What can I use Actors for?
What can I use Actors for? In different scenarios, an Actor may be an alternative to:
What can I use Actors for? In different scenarios, an Actor may be an alternative to:  -   a thread
What can I use Actors for? In different scenarios, an Actor may be an alternative to:  -   a thread  -   an object instanc...
What can I use Actors for? In different scenarios, an Actor may be an alternative to:  -   a thread  -   an object instanc...
What can I use Actors for? In different scenarios, an Actor may be an alternative to:  -   a thread  -   an object instanc...
What can I use Actors for? In different scenarios, an Actor may be an alternative to:  -   a thread  -   an object instanc...
What can I use Actors for? In different scenarios, an Actor may be an alternative to:  -   a thread  -   an object instanc...
What can I use Actors for? In different scenarios, an Actor may be an alternative to:  -   a thread  -   an object instanc...
What can I use Actors for? In different scenarios, an Actor may be an alternative to:  -   a thread  -   an object instanc...
So, what is theActor Model?
Carl Hewitt’s definition    http://bit.ly/hewitt-on-actors
Carl Hewitt’s definition-   The fundamental unit of computation that embodies:                http://bit.ly/hewitt-on-actors
Carl Hewitt’s definition-   The fundamental unit of computation that embodies:    -   Processing                     http:/...
Carl Hewitt’s definition-   The fundamental unit of computation that embodies:    -   Processing    -   Storage            ...
Carl Hewitt’s definition-   The fundamental unit of computation that embodies:    -   Processing    -   Storage    -   Comm...
Carl Hewitt’s definition-   The fundamental unit of computation that embodies:    -   Processing    -   Storage    -   Comm...
Carl Hewitt’s definition-   The fundamental unit of computation that embodies:    -   Processing    -   Storage    -   Comm...
Carl Hewitt’s definition-   The fundamental unit of computation that embodies:    -   Processing    -   Storage    -   Comm...
Carl Hewitt’s definition-   The fundamental unit of computation that embodies:    -   Processing    -   Storage    -   Comm...
4 core Actor operations       0. DEFINE       1. CREATE       2. SEND       3. BECOME       4. SUPERVISE
0. DEFINEpublic class Greeting implements Serializable {   public final String who;   public Greeting(String who) { this.w...
0. DEFINE                        Define the message(s) the Actor                         should be able to respond topublic...
0. DEFINE                        Define the message(s) the Actor                         should be able to respond topublic...
0. DEFINE                        Define the message(s) the Actor                         should be able to respond topublic...
Scala versioncase class Greeting(who: String)class GreetingActor extends Actor with ActorLogging {  def receive = {    cas...
1. CREATE• CREATE - creates a new instance of an Actor• Extremely lightweight (2.7 Million per Gb RAM)• Very strong encaps...
CREATE Actorpublic class Greeting implements Serializable {   public final String who;   public Greeting(String who) { thi...
CREATE Actorpublic class Greeting implements Serializable {   public final String who;   public Greeting(String who) { thi...
CREATE Actorpublic class Greeting implements Serializable {   public final String who;   public Greeting(String who) { thi...
CREATE Actorpublic class Greeting implements Serializable {   public final String who;   public Greeting(String who) { thi...
CREATE Actorpublic class Greeting implements Serializable {   public final String who;   public Greeting(String who) { thi...
CREATE Actorpublic class Greeting implements Serializable {   public final String who;   public Greeting(String who) { thi...
Actors can form hierarchies          Guardian System Actor
Actors can form hierarchies          Guardian System Actor          system.actorOf(Props[Foo], “Foo”)
Actors can form hierarchies             Guardian System Actor       Foo   system.actorOf(Props[Foo], “Foo”)
Actors can form hierarchies               Guardian System Actor       Foo             context.actorOf(Props[A], “A”)
Actors can form hierarchies               Guardian System Actor       Foo      A      context.actorOf(Props[A], “A”)
Actors can form hierarchies             Guardian System Actor       Foo                           Bar                     ...
Name resolution - like a file-system                Guardian System Actor          Foo                           Bar       ...
Name resolution - like a file-system                     Guardian System Actor        /Foo               Foo               ...
Name resolution - like a file-system                         Guardian System Actor            /Foo                   Foo   ...
Name resolution - like a file-system                             Guardian System Actor                /Foo                 ...
Name resolution - like a file-system                                Guardian System Actor                   /Foo           ...
2. SEND
2. SEND• SEND - sends a message to an Actor
2. SEND• SEND - sends a message to an Actor• Asynchronous and Non-blocking - Fire-forget
2. SEND• SEND - sends a message to an Actor• Asynchronous and Non-blocking - Fire-forget• Everything happens Reactively
2. SEND• SEND - sends a message to an Actor• Asynchronous and Non-blocking - Fire-forget• Everything happens Reactively - ...
2. SEND• SEND - sends a message to an Actor• Asynchronous and Non-blocking - Fire-forget• Everything happens Reactively - ...
2. SEND• SEND - sends a message to an Actor• Asynchronous and Non-blocking - Fire-forget• Everything happens Reactively - ...
2. SEND• SEND - sends a message to an Actor• Asynchronous and Non-blocking - Fire-forget• Everything happens Reactively - ...
Throughput on a single box  +50 million messages per second
SEND messagepublic class Greeting implements Serializable {   public final String who;   public Greeting(String who) { thi...
SEND messagepublic class Greeting implements Serializable {   public final String who;   public Greeting(String who) { thi...
Full examplepublic class Greeting implements Serializable {   public final String who;   public Greeting(String who) { thi...
Scala versioncase class Greeting(who: String)class GreetingActor extends Actor with ActorLogging {  def receive = {    cas...
Replyclass SomeActor extends UntypedActor {  void onReceive(Object msg) {    if (msg instanceof User) {      User user = (...
Scala versionclass SomeActor extends Actor {  def receive = {    case User(name) =>      // reply to sender      sender te...
Remote deploymentJust feed the ActorSystem with this configuration   akka {     actor {       provider =    akka.remote.Rem...
Remote deploymentJust feed the ActorSystem with this configuration                                       Configure a Remote ...
Remote deployment     Just feed the ActorSystem with this configuration                                                  Co...
Remote deployment     Just feed the ActorSystem with this configuration                                                  Co...
Remote deployment    Just feed the ActorSystem with this configuration                                             Configure...
Remote deployment    Just feed the ActorSystem with this configuration                                             Configure...
Remote deployment    Just feed the ActorSystem with this configuration                                             Configure...
Remote deployment     Just feed the ActorSystem with this configuration                                              Configu...
Remote deployment     Just feed the ActorSystem with this configuration                                              Configu...
3. BECOME
3. BECOME• BECOME - dynamically redefines Actor’s behavior
3. BECOME• BECOME - dynamically redefines Actor’s behavior• Triggered reactively by receive of message
3. BECOME• BECOME - dynamically redefines Actor’s behavior• Triggered reactively by receive of message• In a type system an...
3. BECOME• BECOME - dynamically redefines Actor’s behavior• Triggered reactively by receive of message• In a type system an...
3. BECOME• BECOME - dynamically redefines Actor’s behavior• Triggered reactively by receive of message• In a type system an...
Why would I want to do that?
Why would I want to do that?• Let a highly contended Actor adaptively transform  himself into an Actor Pool or a Router
Why would I want to do that?• Let a highly contended Actor adaptively transform  himself into an Actor Pool or a Router• I...
Why would I want to do that?• Let a highly contended Actor adaptively transform  himself into an Actor Pool or a Router• I...
Why would I want to do that?• Let a highly contended Actor adaptively transform  himself into an Actor Pool or a Router• I...
Why would I want to do that?• Let a highly contended Actor adaptively transform  himself into an Actor Pool or a Router• I...
Why would I want to do that?• Let a highly contended Actor adaptively transform  himself into an Actor Pool or a Router• I...
becomecontext.become(new Procedure[Object]() {  void apply(Object msg) {    // new body    if (msg instanceof NewMessage) ...
Actor context available                          become from within an Actor         context.become(new Procedure[Object](...
Scala version  context become {    // new body    case NewMessage =>      ...  }
Load Balancing
Routersval router = system.actorOf(   Props[SomeActor].withRouter(    RoundRobinRouter(nrOfInstances = 5)))               ...
Router + Resizerval resizer =  DefaultResizer(lowerBound = 2, upperBound = 15)val router =  system.actorOf(    Props[Examp...
Failure management in Java/C/C# etc.
Failure management in Java/C/C# etc.   • You are given a SINGLE thread of control
Failure management in Java/C/C# etc.   • You are given a SINGLE thread of control   • If this thread blows up you are scre...
Failure management in Java/C/C# etc.   • You are given a SINGLE thread of control   • If this thread blows up you are scre...
Failure management in Java/C/C# etc.   • You are given a SINGLE thread of control   • If this thread blows up you are scre...
Failure management in Java/C/C# etc.   • You are given a SINGLE thread of control   • If this thread blows up you are scre...
Failure management in Java/C/C# etc.   • You are given a SINGLE thread of control   • If this thread blows up you are scre...
Failure management in Java/C/C# etc.   • You are given a SINGLE thread of control   • If this thread blows up you are scre...
Failure management in Java/C/C# etc.   • You are given a SINGLE thread of control   • If this thread blows up you are scre...
4. SUPERVISE
4. SUPERVISE• SUPERVISE - manage another Actor’s failures
4. SUPERVISE• SUPERVISE - manage another Actor’s failures• Error handling in actors is handle by letting Actors  monitor (...
4. SUPERVISE• SUPERVISE - manage another Actor’s failures• Error handling in actors is handle by letting Actors  monitor (...
4. SUPERVISE• SUPERVISE - manage another Actor’s failures• Error handling in actors is handle by letting Actors  monitor (...
...let’s take astandard OO  application
Which components havecritically important state            and explicit error handling?
Fault-tolerant onion-layered Error Kernel
ErrorKernel
ErrorKernel
ErrorKernel
ErrorKernel
ErrorKernel
ErrorKernel
Node 1   Node 2ErrorKernel
SUPERVISE Actor   Every single actor has a default supervisor strategy. Which is usually sufficient.  But it can be overrid...
SUPERVISE Actor                  Every single actor has a                default supervisor strategy.                Which...
SUPERVISE Actorclass Supervisor extends UntypedActor {  private SupervisorStrategy strategy = new OneForOneStrategy(    10...
Scala versionclass Supervisor extends Actor {  override val supervisorStrategy =                     (maxNrOfRetries = 10,...
Scala versionclass Supervisor extends Actor {  override val supervisorStrategy =    OneForOneStrategy(maxNrOfRetries = 10,...
Scala versionclass Supervisor extends Actor {  override val supervisorStrategy =    AllForOneStrategy(maxNrOfRetries = 10,...
Manage failureclass Worker extends Actor {  ...    override def preRestart(      reason: Throwable, message: Option[Any]) ...
This wasAkka 2.x
This was  Akka 2.xWell...it’s a start...
...we have much much more
...we have much much moreTestKit           Cluster                      FSM                                    IO    HTTP/...
get it and learn more       http://akka.io    http://letitcrash.com    http://typesafe.com
EOF
Introducing Akka
Introducing Akka
Introducing Akka
Introducing Akka
Introducing Akka
Introducing Akka
Introducing Akka
Introducing Akka
Introducing Akka
Upcoming SlideShare
Loading in...5
×

Introducing Akka

13,340

Published on

Introduction to Akka 2. Explains what Akka's actors are all about and how to utilize them to write scalable and fault-tolerant systems.
Talk given at JavaZone 2012.

5 Comments
108 Likes
Statistics
Notes
No Downloads
Views
Total Views
13,340
On Slideshare
0
From Embeds
0
Number of Embeds
4
Actions
Shares
0
Downloads
787
Comments
5
Likes
108
Embeds 0
No embeds

No notes for slide

Introducing Akka

  1. 1. Introducing Jonas Bonér CTO Typesafe
  2. 2. Introducing
  3. 3. Introducing Akka (Áhkká) The name comes from the goddess in the Sami (native swedes) mythology that represented all the wisdom and beauty in the world. It is also the name of a beautiful mountain in Laponia in the north part of Sweden
  4. 4. Introducing
  5. 5. VisionSimpler Concurrency Scalability Fault-tolerance
  6. 6. Vision...with a single unified Programming Model Managed Runtime Open Source Distribution
  7. 7. Manage System Overload
  8. 8. Scale UP & Scale OUT
  9. 9. Program at a Higher Level
  10. 10. Program at a Higher Level
  11. 11. Program at a Higher Level• Never think in terms of shared state, state visibility, threads, locks, concurrent collections, thread notifications etc.
  12. 12. Program at a Higher Level• Never think in terms of shared state, state visibility, threads, locks, concurrent collections, thread notifications etc.• Low level concurrency plumbing BECOMES SIMPLE WORKFLOW - you only think about how messages flow in the system
  13. 13. Program at a Higher Level• Never think in terms of shared state, state visibility, threads, locks, concurrent collections, thread notifications etc.• Low level concurrency plumbing BECOMES SIMPLE WORKFLOW - you only think about how messages flow in the system• You get high CPU utilization, low latency, high throughput and scalability - FOR FREE as part of the model
  14. 14. Program at a Higher Level• Never think in terms of shared state, state visibility, threads, locks, concurrent collections, thread notifications etc.• Low level concurrency plumbing BECOMES SIMPLE WORKFLOW - you only think about how messages flow in the system• You get high CPU utilization, low latency, high throughput and scalability - FOR FREE as part of the model• Proven and superior model for detecting and recovering from errors
  15. 15. Distributable by Design
  16. 16. Distributable by Design
  17. 17. Distributable by Design• Actors are location transparent & distributable by design
  18. 18. Distributable by Design• Actors are location transparent & distributable by design• Scale UP and OUT for free as part of the model
  19. 19. Distributable by Design• Actors are location transparent & distributable by design• Scale UP and OUT for free as part of the model• You get the PERFECT FABRIC for the CLOUD
  20. 20. Distributable by Design• Actors are location transparent & distributable by design• Scale UP and OUT for free as part of the model• You get the PERFECT FABRIC for the CLOUD - elastic & dynamic
  21. 21. Distributable by Design• Actors are location transparent & distributable by design• Scale UP and OUT for free as part of the model• You get the PERFECT FABRIC for the CLOUD - elastic & dynamic - fault-tolerant & self-healing
  22. 22. Distributable by Design• Actors are location transparent & distributable by design• Scale UP and OUT for free as part of the model• You get the PERFECT FABRIC for the CLOUD - elastic & dynamic - fault-tolerant & self-healing - adaptive load-balancing, cluster rebalancing & actor migration
  23. 23. Distributable by Design• Actors are location transparent & distributable by design• Scale UP and OUT for free as part of the model• You get the PERFECT FABRIC for the CLOUD - elastic & dynamic - fault-tolerant & self-healing - adaptive load-balancing, cluster rebalancing & actor migration - build extremely loosely coupled and dynamic systems that can change and adapt at runtime
  24. 24. Selection of Akka Production Users
  25. 25. Howcan we achieve this?
  26. 26. Howcan we achieve this?
  27. 27. Let’s use Actors Howcan we achieve this?
  28. 28. What is an Actor?
  29. 29. What is an Actor?
  30. 30. What is an Actor?• Akkas unit of code organization is called an Actor
  31. 31. What is an Actor?• Akkas unit of code organization is called an Actor• Actors helps you create concurrent, scalable and fault-tolerant applications
  32. 32. What is an Actor?• Akkas unit of code organization is called an Actor• Actors helps you create concurrent, scalable and fault-tolerant applications• Like Java EE servlets and session beans, Actors is a model for organizing your code that keeps many “policy decisions” separate from the business logic
  33. 33. What is an Actor?• Akkas unit of code organization is called an Actor• Actors helps you create concurrent, scalable and fault-tolerant applications• Like Java EE servlets and session beans, Actors is a model for organizing your code that keeps many “policy decisions” separate from the business logic• Actors may be new to many in the Java community, but they are a tried-and-true concept (Hewitt 1973) used for many years in telecom systems with 9 nines uptime
  34. 34. Actors can be seen asVirtual Machines (nodes) in Cloud Computing
  35. 35. Encapsulatedand decoupled black boxes...
  36. 36. Encapsulatedand decoupled black boxes...
  37. 37. ...that manages their own memory and behavior
  38. 38. ...that manages their own memory and behavior
  39. 39. Communicateswith asynchronous non-blocking messages
  40. 40. Communicateswith asynchronous non-blocking messages
  41. 41. Elastic - grow andshrink on demand
  42. 42. Elastic - grow andshrink on demand
  43. 43. Elastic - grow andshrink on demand
  44. 44. Elastic - grow andshrink on demand
  45. 45. Hot deploy - changebehavior at runtime
  46. 46. Hot deploy - changebehavior at runtime
  47. 47. Now - if we replace with ActorEVERYTHING will STILL HOLD for both LOCAL and DISTRIBUTED Actors
  48. 48. What can I use Actors for?
  49. 49. What can I use Actors for? In different scenarios, an Actor may be an alternative to:
  50. 50. What can I use Actors for? In different scenarios, an Actor may be an alternative to: - a thread
  51. 51. What can I use Actors for? In different scenarios, an Actor may be an alternative to: - a thread - an object instance or component
  52. 52. What can I use Actors for? In different scenarios, an Actor may be an alternative to: - a thread - an object instance or component - a callback or listener
  53. 53. What can I use Actors for? In different scenarios, an Actor may be an alternative to: - a thread - an object instance or component - a callback or listener - a singleton or service
  54. 54. What can I use Actors for? In different scenarios, an Actor may be an alternative to: - a thread - an object instance or component - a callback or listener - a singleton or service - a router, load-balancer or pool
  55. 55. What can I use Actors for? In different scenarios, an Actor may be an alternative to: - a thread - an object instance or component - a callback or listener - a singleton or service - a router, load-balancer or pool - a Java EE Session Bean or Message-Driven Bean
  56. 56. What can I use Actors for? In different scenarios, an Actor may be an alternative to: - a thread - an object instance or component - a callback or listener - a singleton or service - a router, load-balancer or pool - a Java EE Session Bean or Message-Driven Bean - an out-of-process service
  57. 57. What can I use Actors for? In different scenarios, an Actor may be an alternative to: - a thread - an object instance or component - a callback or listener - a singleton or service - a router, load-balancer or pool - a Java EE Session Bean or Message-Driven Bean - an out-of-process service - a Finite State Machine (FSM)
  58. 58. So, what is theActor Model?
  59. 59. Carl Hewitt’s definition http://bit.ly/hewitt-on-actors
  60. 60. Carl Hewitt’s definition- The fundamental unit of computation that embodies: http://bit.ly/hewitt-on-actors
  61. 61. Carl Hewitt’s definition- The fundamental unit of computation that embodies: - Processing http://bit.ly/hewitt-on-actors
  62. 62. Carl Hewitt’s definition- The fundamental unit of computation that embodies: - Processing - Storage http://bit.ly/hewitt-on-actors
  63. 63. Carl Hewitt’s definition- The fundamental unit of computation that embodies: - Processing - Storage - Communication http://bit.ly/hewitt-on-actors
  64. 64. Carl Hewitt’s definition- The fundamental unit of computation that embodies: - Processing - Storage - Communication- 3 axioms - When an Actor receives a message it can: http://bit.ly/hewitt-on-actors
  65. 65. Carl Hewitt’s definition- The fundamental unit of computation that embodies: - Processing - Storage - Communication- 3 axioms - When an Actor receives a message it can: - Create new Actors http://bit.ly/hewitt-on-actors
  66. 66. Carl Hewitt’s definition- The fundamental unit of computation that embodies: - Processing - Storage - Communication- 3 axioms - When an Actor receives a message it can: - Create new Actors - Send messages to Actors it knows http://bit.ly/hewitt-on-actors
  67. 67. Carl Hewitt’s definition- The fundamental unit of computation that embodies: - Processing - Storage - Communication- 3 axioms - When an Actor receives a message it can: - Create new Actors - Send messages to Actors it knows - Designate how it should handle the next message it receives http://bit.ly/hewitt-on-actors
  68. 68. 4 core Actor operations 0. DEFINE 1. CREATE 2. SEND 3. BECOME 4. SUPERVISE
  69. 69. 0. DEFINEpublic class Greeting implements Serializable { public final String who; public Greeting(String who) { this.who = who; }}public class GreetingActor extends UntypedActor { LoggingAdapter log = Logging.getLogger(getContext().system(), this); public void onReceive(Object message) throws Exception { if (message instanceof Greeting) log.info("Hello {}", ((Greeting) message).who); } }}
  70. 70. 0. DEFINE Define the message(s) the Actor should be able to respond topublic class Greeting implements Serializable { public final String who; public Greeting(String who) { this.who = who; }}public class GreetingActor extends UntypedActor { LoggingAdapter log = Logging.getLogger(getContext().system(), this); public void onReceive(Object message) throws Exception { if (message instanceof Greeting) log.info("Hello {}", ((Greeting) message).who); } }}
  71. 71. 0. DEFINE Define the message(s) the Actor should be able to respond topublic class Greeting implements Serializable { public final String who; Define the Actor class public Greeting(String who) { this.who = who; }}public class GreetingActor extends UntypedActor { LoggingAdapter log = Logging.getLogger(getContext().system(), this); public void onReceive(Object message) throws Exception { if (message instanceof Greeting) log.info("Hello {}", ((Greeting) message).who); } }}
  72. 72. 0. DEFINE Define the message(s) the Actor should be able to respond topublic class Greeting implements Serializable { public final String who; Define the Actor class public Greeting(String who) { this.who = who; }}public class GreetingActor extends UntypedActor { LoggingAdapter log = Logging.getLogger(getContext().system(), this); public void onReceive(Object message) throws Exception { if (message instanceof Greeting) log.info("Hello {}", ((Greeting) message).who); } } Define the Actor’s behavior}
  73. 73. Scala versioncase class Greeting(who: String)class GreetingActor extends Actor with ActorLogging { def receive = { case Greeting(who) => log.info("Hello {}", who) }}
  74. 74. 1. CREATE• CREATE - creates a new instance of an Actor• Extremely lightweight (2.7 Million per Gb RAM)• Very strong encapsulation - encapsulates: -  state -  behavior -  message queue• State & behavior is indistinguishable from each other• Only way to observe state is by sending an actor a message and see how it reacts
  75. 75. CREATE Actorpublic class Greeting implements Serializable { public final String who; public Greeting(String who) { this.who = who; }}public class GreetingActor extends UntypedActor { LoggingAdapter log = Logging.getLogger(getContext().system(), this); public void onReceive(Object message) throws Exception { if (message instanceof Greeting) log.info("Hello {}", ((Greeting) message).who); } }}ActorSystem system = ActorSystem.create("MySystem");ActorRef greeter = system.actorOf(new Props(GreetingActor.class), "greeter");
  76. 76. CREATE Actorpublic class Greeting implements Serializable { public final String who; public Greeting(String who) { this.who = who; }}public class GreetingActor extends UntypedActor { LoggingAdapter log = Logging.getLogger(getContext().system(), this); public void onReceive(Object message) throws Exception { if (message instanceof Greeting) log.info("Hello {}", ((Greeting) message).who); } Create an Actor system }}ActorSystem system = ActorSystem.create("MySystem");ActorRef greeter = system.actorOf(new Props(GreetingActor.class), "greeter");
  77. 77. CREATE Actorpublic class Greeting implements Serializable { public final String who; public Greeting(String who) { this.who = who; }}public class GreetingActor extends UntypedActor { LoggingAdapter log = Logging.getLogger(getContext().system(), this); public void onReceive(Object message) throws Exception { if (message instanceof Greeting) log.info("Hello {}", ((Greeting) message).who); } Create an Actor system } Actor configuration}ActorSystem system = ActorSystem.create("MySystem");ActorRef greeter = system.actorOf(new Props(GreetingActor.class), "greeter");
  78. 78. CREATE Actorpublic class Greeting implements Serializable { public final String who; public Greeting(String who) { this.who = who; }}public class GreetingActor extends UntypedActor { LoggingAdapter log = Logging.getLogger(getContext().system(), this); public void onReceive(Object message) throws Exception { if (message instanceof Greeting) log.info("Hello {}", ((Greeting) message).who); } Create an Actor system } Actor configuration}ActorSystem system = ActorSystem.create("MySystem");ActorRef greeter = system.actorOf(new Props(GreetingActor.class), "greeter"); Give it a name
  79. 79. CREATE Actorpublic class Greeting implements Serializable { public final String who; public Greeting(String who) { this.who = who; }}public class GreetingActor extends UntypedActor { LoggingAdapter log = Logging.getLogger(getContext().system(), this); public void onReceive(Object message) throws Exception { if (message instanceof Greeting) log.info("Hello {}", ((Greeting) message).who); } Create an Actor system } Actor configuration}ActorSystem system = ActorSystem.create("MySystem");ActorRef greeter = system.actorOf(new Props(GreetingActor.class), "greeter"); Create the Actor Give it a name
  80. 80. CREATE Actorpublic class Greeting implements Serializable { public final String who; public Greeting(String who) { this.who = who; }}public class GreetingActor extends UntypedActor { LoggingAdapter log = Logging.getLogger(getContext().system(), this); public void onReceive(Object message) throws Exception { if (message instanceof Greeting) log.info("Hello {}", ((Greeting) message).who); } Create an Actor system } Actor configuration}ActorSystem system = ActorSystem.create("MySystem");ActorRef greeter = system.actorOf(new Props(GreetingActor.class), "greeter"); Create the Actor You get an ActorRef back Give it a name
  81. 81. Actors can form hierarchies Guardian System Actor
  82. 82. Actors can form hierarchies Guardian System Actor system.actorOf(Props[Foo], “Foo”)
  83. 83. Actors can form hierarchies Guardian System Actor Foo system.actorOf(Props[Foo], “Foo”)
  84. 84. Actors can form hierarchies Guardian System Actor Foo context.actorOf(Props[A], “A”)
  85. 85. Actors can form hierarchies Guardian System Actor Foo A context.actorOf(Props[A], “A”)
  86. 86. Actors can form hierarchies Guardian System Actor Foo Bar A A C E CB B D
  87. 87. Name resolution - like a file-system Guardian System Actor Foo Bar A A C E C B B D
  88. 88. Name resolution - like a file-system Guardian System Actor /Foo Foo Bar A A C E C B B D
  89. 89. Name resolution - like a file-system Guardian System Actor /Foo Foo Bar /Foo/A A A C E C B B D
  90. 90. Name resolution - like a file-system Guardian System Actor /Foo Foo Bar /Foo/A A A C /Foo/A/B E C B B D
  91. 91. Name resolution - like a file-system Guardian System Actor /Foo Foo Bar /Foo/A A A C /Foo/A/B E C B B D /Foo/A/D
  92. 92. 2. SEND
  93. 93. 2. SEND• SEND - sends a message to an Actor
  94. 94. 2. SEND• SEND - sends a message to an Actor• Asynchronous and Non-blocking - Fire-forget
  95. 95. 2. SEND• SEND - sends a message to an Actor• Asynchronous and Non-blocking - Fire-forget• Everything happens Reactively
  96. 96. 2. SEND• SEND - sends a message to an Actor• Asynchronous and Non-blocking - Fire-forget• Everything happens Reactively - An Actor is passive until a message is sent to it, which triggers something within the Actor
  97. 97. 2. SEND• SEND - sends a message to an Actor• Asynchronous and Non-blocking - Fire-forget• Everything happens Reactively - An Actor is passive until a message is sent to it, which triggers something within the Actor - Messages is the Kinetic Energy in an Actor system
  98. 98. 2. SEND• SEND - sends a message to an Actor• Asynchronous and Non-blocking - Fire-forget• Everything happens Reactively - An Actor is passive until a message is sent to it, which triggers something within the Actor - Messages is the Kinetic Energy in an Actor system - Actors can have lots of buffered Potential Energy but cant do anything with it until it is triggered by a message
  99. 99. 2. SEND• SEND - sends a message to an Actor• Asynchronous and Non-blocking - Fire-forget• Everything happens Reactively - An Actor is passive until a message is sent to it, which triggers something within the Actor - Messages is the Kinetic Energy in an Actor system - Actors can have lots of buffered Potential Energy but cant do anything with it until it is triggered by a message• EVERYTHING is asynchronous and lockless
  100. 100. Throughput on a single box +50 million messages per second
  101. 101. SEND messagepublic class Greeting implements Serializable { public final String who; public Greeting(String who) { this.who = who; }}public class GreetingActor extends UntypedActor { LoggingAdapter log = Logging.getLogger(getContext().system(), this); public void onReceive(Object message) throws Exception { if (message instanceof Greeting) log.info("Hello {}", ((Greeting) message).who); } }}ActorSystem system = ActorSystem.create("MySystem");ActorRef greeter = system.actorOf(new Props(GreetingActor.class), "greeter");greeter.tell(new Greeting("Charlie Parker"));
  102. 102. SEND messagepublic class Greeting implements Serializable { public final String who; public Greeting(String who) { this.who = who; }}public class GreetingActor extends UntypedActor { LoggingAdapter log = Logging.getLogger(getContext().system(), this); public void onReceive(Object message) throws Exception { if (message instanceof Greeting) log.info("Hello {}", ((Greeting) message).who); } }}ActorSystem system = ActorSystem.create("MySystem");ActorRef greeter = system.actorOf(new Props(GreetingActor.class), "greeter");greeter.tell(new Greeting("Charlie Parker")); Send the message
  103. 103. Full examplepublic class Greeting implements Serializable { public final String who; public Greeting(String who) { this.who = who; }}public class GreetingActor extends UntypedActor { LoggingAdapter log = Logging.getLogger(getContext().system(), this); public void onReceive(Object message) throws Exception { if (message instanceof Greeting) log.info("Hello {}", ((Greeting) message).who); } }}ActorSystem system = ActorSystem.create("MySystem");ActorRef greeter = system.actorOf(new Props(GreetingActor.class), "greeter");greeter.tell(new Greeting("Charlie Parker"));
  104. 104. Scala versioncase class Greeting(who: String)class GreetingActor extends Actor with ActorLogging { def receive = { case Greeting(who) => log.info("Hello {}", who) }}val system = ActorSystem("MySystem")val greeter = system.actorOf(Props[GreetingActor], name = "greeter")greeter tell Greeting("Charlie Parker")
  105. 105. Replyclass SomeActor extends UntypedActor { void onReceive(Object msg) { if (msg instanceof User) { User user = (User) msg; // reply to sender getSender().tell(“Hi ” + user.name); } }}
  106. 106. Scala versionclass SomeActor extends Actor { def receive = { case User(name) => // reply to sender sender tell (“Hi ” + name) }}
  107. 107. Remote deploymentJust feed the ActorSystem with this configuration akka { actor { provider = akka.remote.RemoteActorRefProvider deployment { /Greeter { remote = } } } }
  108. 108. Remote deploymentJust feed the ActorSystem with this configuration Configure a Remote Provider akka { actor { provider = akka.remote.RemoteActorRefProvider deployment { /Greeter { remote = } } } }
  109. 109. Remote deployment Just feed the ActorSystem with this configuration Configure a Remote Provider akka {For the Greeter actor { actor provider = akka.remote.RemoteActorRefProvider deployment { /Greeter { remote = } } } }
  110. 110. Remote deployment Just feed the ActorSystem with this configuration Configure a Remote Provider akka {For the Greeter actor { actor provider = akka.remote.RemoteActorRefProvider deployment { /Greeter { remote = } } Define Remote Path } }
  111. 111. Remote deployment Just feed the ActorSystem with this configuration Configure a Remote Provider akka {For the Greeter actor { actor provider = akka.remote.RemoteActorRefProvider deployment { /Greeter { remote = akka:// } } Define Remote Path } Protocol }
  112. 112. Remote deployment Just feed the ActorSystem with this configuration Configure a Remote Provider akka {For the Greeter actor { actor provider = akka.remote.RemoteActorRefProvider deployment { /Greeter { remote = akka://MySystem } } Define Remote Path } Protocol Actor System }
  113. 113. Remote deployment Just feed the ActorSystem with this configuration Configure a Remote Provider akka {For the Greeter actor { actor provider = akka.remote.RemoteActorRefProvider deployment { /Greeter { remote = akka://MySystem@machine1 } } Define Remote Path } Protocol Actor System Hostname }
  114. 114. Remote deployment Just feed the ActorSystem with this configuration Configure a Remote Provider akka {For the Greeter actor { actor provider = akka.remote.RemoteActorRefProvider deployment { /Greeter { remote = akka://MySystem@machine1:2552 } } Define Remote Path } Protocol Actor System Hostname Port }
  115. 115. Remote deployment Just feed the ActorSystem with this configuration Configure a Remote Provider akka {For the Greeter actor { actor provider = akka.remote.RemoteActorRefProvider deployment { /Greeter { remote = akka://MySystem@machine1:2552 } } Define Remote Path } Protocol Actor System Hostname Port } Zero code changes
  116. 116. 3. BECOME
  117. 117. 3. BECOME• BECOME - dynamically redefines Actor’s behavior
  118. 118. 3. BECOME• BECOME - dynamically redefines Actor’s behavior• Triggered reactively by receive of message
  119. 119. 3. BECOME• BECOME - dynamically redefines Actor’s behavior• Triggered reactively by receive of message• In a type system analogy it is as if the object changed type - changed interface, protocol & implementation
  120. 120. 3. BECOME• BECOME - dynamically redefines Actor’s behavior• Triggered reactively by receive of message• In a type system analogy it is as if the object changed type - changed interface, protocol & implementation• Will now react differently to the messages it receives
  121. 121. 3. BECOME• BECOME - dynamically redefines Actor’s behavior• Triggered reactively by receive of message• In a type system analogy it is as if the object changed type - changed interface, protocol & implementation• Will now react differently to the messages it receives• Behaviors are stacked & can be pushed and popped
  122. 122. Why would I want to do that?
  123. 123. Why would I want to do that?• Let a highly contended Actor adaptively transform himself into an Actor Pool or a Router
  124. 124. Why would I want to do that?• Let a highly contended Actor adaptively transform himself into an Actor Pool or a Router• Implement an FSM (Finite State Machine)
  125. 125. Why would I want to do that?• Let a highly contended Actor adaptively transform himself into an Actor Pool or a Router• Implement an FSM (Finite State Machine)• Implement graceful degradation
  126. 126. Why would I want to do that?• Let a highly contended Actor adaptively transform himself into an Actor Pool or a Router• Implement an FSM (Finite State Machine)• Implement graceful degradation• Spawn up (empty) generic Worker processes that can become whatever the Master currently needs
  127. 127. Why would I want to do that?• Let a highly contended Actor adaptively transform himself into an Actor Pool or a Router• Implement an FSM (Finite State Machine)• Implement graceful degradation• Spawn up (empty) generic Worker processes that can become whatever the Master currently needs• etc. use your imagination
  128. 128. Why would I want to do that?• Let a highly contended Actor adaptively transform himself into an Actor Pool or a Router• Implement an FSM (Finite State Machine)• Implement graceful degradation• Spawn up (empty) generic Worker processes that can become whatever the Master currently needs• etc. use your imagination• Very useful once you get the used to it
  129. 129. becomecontext.become(new Procedure[Object]() { void apply(Object msg) { // new body if (msg instanceof NewMessage) { NewMessage newMsg = (NewMessage)msg; ... } }});
  130. 130. Actor context available become from within an Actor context.become(new Procedure[Object]() { void apply(Object msg) { // new body if (msg instanceof NewMessage) { NewMessage newMsg = (NewMessage)msg; ... } } });
  131. 131. Scala version context become { // new body case NewMessage => ... }
  132. 132. Load Balancing
  133. 133. Routersval router = system.actorOf( Props[SomeActor].withRouter( RoundRobinRouter(nrOfInstances = 5))) Scala API
  134. 134. Router + Resizerval resizer = DefaultResizer(lowerBound = 2, upperBound = 15)val router = system.actorOf( Props[ExampleActor1].withRouter( RoundRobinRouter(resizer = Some(resizer)))) Scala API
  135. 135. Failure management in Java/C/C# etc.
  136. 136. Failure management in Java/C/C# etc. • You are given a SINGLE thread of control
  137. 137. Failure management in Java/C/C# etc. • You are given a SINGLE thread of control • If this thread blows up you are screwed
  138. 138. Failure management in Java/C/C# etc. • You are given a SINGLE thread of control • If this thread blows up you are screwed • So you need to do all explicit error handling WITHIN this single thread
  139. 139. Failure management in Java/C/C# etc. • You are given a SINGLE thread of control • If this thread blows up you are screwed • So you need to do all explicit error handling WITHIN this single thread • To make things worse - errors do not propagate between threads so there is NO WAY OF EVEN FINDING OUT that something have failed
  140. 140. Failure management in Java/C/C# etc. • You are given a SINGLE thread of control • If this thread blows up you are screwed • So you need to do all explicit error handling WITHIN this single thread • To make things worse - errors do not propagate between threads so there is NO WAY OF EVEN FINDING OUT that something have failed • This leads to DEFENSIVE programming with:
  141. 141. Failure management in Java/C/C# etc. • You are given a SINGLE thread of control • If this thread blows up you are screwed • So you need to do all explicit error handling WITHIN this single thread • To make things worse - errors do not propagate between threads so there is NO WAY OF EVEN FINDING OUT that something have failed • This leads to DEFENSIVE programming with: • Error handling TANGLED with business logic
  142. 142. Failure management in Java/C/C# etc. • You are given a SINGLE thread of control • If this thread blows up you are screwed • So you need to do all explicit error handling WITHIN this single thread • To make things worse - errors do not propagate between threads so there is NO WAY OF EVEN FINDING OUT that something have failed • This leads to DEFENSIVE programming with: • Error handling TANGLED with business logic • SCATTERED all over the code base
  143. 143. Failure management in Java/C/C# etc. • You are given a SINGLE thread of control • If this thread blows up you are screwed • So you need to do all explicit error handling WITHIN this single thread • To make things worse - errors do not propagate between threads so there is NO WAY OF EVEN FINDING OUT that something have failed • This leads to DEFENSIVE programming with: • Error handling TANGLED with business logic • SCATTERED all over the code base We can do better than this!!!
  144. 144. 4. SUPERVISE
  145. 145. 4. SUPERVISE• SUPERVISE - manage another Actor’s failures
  146. 146. 4. SUPERVISE• SUPERVISE - manage another Actor’s failures• Error handling in actors is handle by letting Actors monitor (supervise) each other for failure
  147. 147. 4. SUPERVISE• SUPERVISE - manage another Actor’s failures• Error handling in actors is handle by letting Actors monitor (supervise) each other for failure• This means that if an Actor crashes, a notification will be sent to his supervisor, who can react upon the failure
  148. 148. 4. SUPERVISE• SUPERVISE - manage another Actor’s failures• Error handling in actors is handle by letting Actors monitor (supervise) each other for failure• This means that if an Actor crashes, a notification will be sent to his supervisor, who can react upon the failure• This provides clean separation of processing and error handling
  149. 149. ...let’s take astandard OO application
  150. 150. Which components havecritically important state and explicit error handling?
  151. 151. Fault-tolerant onion-layered Error Kernel
  152. 152. ErrorKernel
  153. 153. ErrorKernel
  154. 154. ErrorKernel
  155. 155. ErrorKernel
  156. 156. ErrorKernel
  157. 157. ErrorKernel
  158. 158. Node 1 Node 2ErrorKernel
  159. 159. SUPERVISE Actor Every single actor has a default supervisor strategy. Which is usually sufficient. But it can be overridden.
  160. 160. SUPERVISE Actor Every single actor has a default supervisor strategy. Which is usually sufficient. But it can be overridden.class Supervisor extends UntypedActor { private SupervisorStrategy strategy = new OneForOneStrategy( 10, Duration.parse("1 minute"), new Function<Throwable, Directive>() { @Override public Directive apply(Throwable t) { if (t instanceof ArithmeticException) return resume(); else if (t instanceof NullPointerException) return restart(); else return escalate(); } }); @Override public SupervisorStrategy supervisorStrategy() {
  161. 161. SUPERVISE Actorclass Supervisor extends UntypedActor { private SupervisorStrategy strategy = new OneForOneStrategy( 10, Duration.parse("1 minute"), new Function<Throwable, Directive>() { @Override public Directive apply(Throwable t) { if (t instanceof ArithmeticException) return resume(); else if (t instanceof NullPointerException) return restart(); else return escalate(); } }); @Override public SupervisorStrategy supervisorStrategy() { return strategy; } ActorRef worker = context.actorOf(new Props(Worker.class)); public void onReceive(Object message) throws Exception { if (message instanceof Integer) worker.forward(message); }}
  162. 162. Scala versionclass Supervisor extends Actor { override val supervisorStrategy = (maxNrOfRetries = 10, withinTimeRange = 1 minute) { case _: ArithmeticException => Resume case _: NullPointerException => Restart case _: Exception => Escalate } val worker = context.actorOf(Props[Worker]) def receive = { case n: Int => worker forward n }}
  163. 163. Scala versionclass Supervisor extends Actor { override val supervisorStrategy = OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 1 minute) { case _: ArithmeticException => Resume case _: NullPointerException => Restart case _: Exception => Escalate } val worker = context.actorOf(Props[Worker]) def receive = { case n: Int => worker forward n }}
  164. 164. Scala versionclass Supervisor extends Actor { override val supervisorStrategy = AllForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 1 minute) { case _: ArithmeticException => Resume case _: NullPointerException => Restart case _: Exception => Escalate } val worker = context.actorOf(Props[Worker]) def receive = { case n: Int => worker forward n }}
  165. 165. Manage failureclass Worker extends Actor { ... override def preRestart( reason: Throwable, message: Option[Any]) { ... // clean up before restart } override def postRestart(reason: Throwable) { ... // init after restart }} Scala API
  166. 166. This wasAkka 2.x
  167. 167. This was Akka 2.xWell...it’s a start...
  168. 168. ...we have much much more
  169. 169. ...we have much much moreTestKit Cluster FSM IO HTTP/REST EventBus Durable Mailboxes Pub/Sub CamelMicrokernel TypedActor SLF4J AMQP ZeroMQ Dataflow TransactorsAgents Spring Extensions
  170. 170. get it and learn more http://akka.io http://letitcrash.com http://typesafe.com
  171. 171. EOF
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×