Introducing Akka

180
Introducing Jonas Bonér CTO Typesafe

description

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.

Transcript of Introducing Akka

Page 1: Introducing Akka

Introducing

Jonas Bonér CTO Typesafe

Page 2: Introducing Akka

Introducing

Page 3: Introducing Akka

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

Page 4: Introducing Akka

Introducing

Page 5: Introducing Akka

Vision

Simpler

Concurrency

Scalability

Fault-tolerance

Page 6: Introducing Akka

Vision

...with a single unified

Programming Model

Managed Runtime

Open Source Distribution

Page 7: Introducing Akka

Manage System Overload

Page 8: Introducing Akka

Scale UP & Scale OUT

Page 9: Introducing Akka

Program at a Higher Level

Page 10: Introducing Akka

Program at a Higher Level

Page 11: Introducing Akka

Program at a Higher Level• Never think in terms of shared state, state

visibility, threads, locks, concurrent collections, thread notifications etc.

Page 12: Introducing Akka

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

Page 13: Introducing Akka

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

Page 14: Introducing Akka

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

Page 15: Introducing Akka

Distributable by Design

Page 16: Introducing Akka

Distributable by Design

Page 17: Introducing Akka

Distributable by Design

• Actors are location transparent & distributable by design

Page 18: Introducing Akka

Distributable by Design

• Actors are location transparent & distributable by design

• Scale UP and OUT for free as part of the model

Page 19: Introducing Akka

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

Page 20: Introducing Akka

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

Page 21: Introducing Akka

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

Page 22: Introducing Akka

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

Page 23: Introducing Akka

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

Page 24: Introducing Akka

Selection of Akka Production Users

Page 25: Introducing Akka
Page 26: Introducing Akka

How can we achieve this?

Page 27: Introducing Akka

How can we achieve this?

Page 28: Introducing Akka

How can we achieve this?

Let’s use Actors

Page 29: Introducing Akka

What is an Actor?

Page 30: Introducing Akka

What is an Actor?

Page 31: Introducing Akka

What is an Actor?

• Akka's unit of code organization is called an Actor

Page 32: Introducing Akka

What is an Actor?

• Akka's unit of code organization is called an Actor

• Actors helps you create concurrent, scalable and fault-tolerant applications

Page 33: Introducing Akka

What is an Actor?

• Akka's 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

Page 34: Introducing Akka

What is an Actor?

• Akka's 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

Page 35: Introducing Akka
Page 36: Introducing Akka

Actors can be seen asVirtual Machines (nodes)

in Cloud Computing

Page 37: Introducing Akka
Page 38: Introducing Akka

Encapsulated and decoupled black boxes...

Page 39: Introducing Akka

Encapsulated and decoupled black boxes...

Page 40: Introducing Akka
Page 41: Introducing Akka

...that manages their own memory and behavior

Page 42: Introducing Akka

...that manages their own memory and behavior

Page 43: Introducing Akka
Page 44: Introducing Akka

Communicates with asynchronous

non-blocking messages

Page 45: Introducing Akka

Communicates with asynchronous

non-blocking messages

Page 46: Introducing Akka
Page 47: Introducing Akka

Elastic - grow and shrink on demand

Page 48: Introducing Akka

Elastic - grow and shrink on demand

Page 49: Introducing Akka

Elastic - grow and shrink on demand

Page 50: Introducing Akka

Elastic - grow and shrink on demand

Page 51: Introducing Akka
Page 52: Introducing Akka

Hot deploy - change behavior at runtime

Page 53: Introducing Akka

Hot deploy - change behavior at runtime

Page 54: Introducing Akka

Now - if we replace

with ActorEVERYTHING will STILL HOLD for both

LOCAL and DISTRIBUTED Actors

Page 55: Introducing Akka

What can I use Actors for?

Page 56: Introducing Akka

What can I use Actors for?In different scenarios, an Actor may be an alternative to:

Page 57: Introducing Akka

What can I use Actors for?In different scenarios, an Actor may be an alternative to:

- a thread

Page 58: Introducing Akka

What can I use Actors for?In different scenarios, an Actor may be an alternative to:

- a thread

- an object instance or component

Page 59: Introducing Akka

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

Page 60: Introducing Akka

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

Page 61: Introducing Akka

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

Page 62: Introducing Akka

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

Page 63: Introducing Akka

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

Page 64: Introducing Akka

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)

Page 65: Introducing Akka

So, what is the

Actor Model?

Page 66: Introducing Akka

Carl Hewitt’s definition

http://bit.ly/hewitt-on-actors

Page 67: Introducing Akka

Carl Hewitt’s definition

http://bit.ly/hewitt-on-actors

- The fundamental unit of computation that embodies:

Page 68: Introducing Akka

Carl Hewitt’s definition

http://bit.ly/hewitt-on-actors

- The fundamental unit of computation that embodies:

- Processing

Page 69: Introducing Akka

Carl Hewitt’s definition

http://bit.ly/hewitt-on-actors

- The fundamental unit of computation that embodies:

- Processing

- Storage

Page 70: Introducing Akka

Carl Hewitt’s definition

http://bit.ly/hewitt-on-actors

- The fundamental unit of computation that embodies:

- Processing

- Storage

- Communication

Page 71: Introducing Akka

Carl Hewitt’s definition

http://bit.ly/hewitt-on-actors

- The fundamental unit of computation that embodies:

- Processing

- Storage

- Communication

- 3 axioms - When an Actor receives a message it can:

Page 72: Introducing Akka

Carl Hewitt’s definition

http://bit.ly/hewitt-on-actors

- The fundamental unit of computation that embodies:

- Processing

- Storage

- Communication

- 3 axioms - When an Actor receives a message it can:

- Create new Actors

Page 73: Introducing Akka

Carl Hewitt’s definition

http://bit.ly/hewitt-on-actors

- 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

Page 74: Introducing Akka

Carl Hewitt’s definition

http://bit.ly/hewitt-on-actors

- 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

Page 75: Introducing Akka

4 core Actor operations

0. DEFINE

1. CREATE

2. SEND

3. BECOME

4. SUPERVISE

Page 76: Introducing Akka

public 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);}

}}

0. DEFINE

Page 77: Introducing Akka

public 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);}

}}

0. DEFINEDefine the message(s) the Actor

should be able to respond to

Page 78: Introducing Akka

public 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);}

}}

0. DEFINEDefine the message(s) the Actor

should be able to respond to

Define the Actor class

Page 79: Introducing Akka

public 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);}

}}

0. DEFINEDefine the message(s) the Actor

should be able to respond to

Define the Actor class

Define the Actor’s behavior

Page 80: Introducing Akka

case class Greeting(who: String)

class GreetingActor extends Actor with ActorLogging { def receive = { case Greeting(who) => log.info("Hello {}", who) }}

Scala version

Page 81: Introducing Akka

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

Page 82: Introducing Akka

public 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");

CREATE Actor

Page 83: Introducing Akka

public 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");

CREATE Actor

Create an Actor system

Page 84: Introducing Akka

public 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");

CREATE Actor

Create an Actor system Actor configuration

Page 85: Introducing Akka

public 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");

CREATE Actor

Create an Actor system Actor configuration

Give it a name

Page 86: Introducing Akka

public 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");

CREATE Actor

Create an Actor system

Create the Actor

Actor configuration

Give it a name

Page 87: Introducing Akka

public 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");

CREATE Actor

Create an Actor system

Create the Actor

Actor configuration

Give it a nameYou get an ActorRef back

Page 88: Introducing Akka

Guardian System Actor

Actors can form hierarchies

Page 89: Introducing Akka

Guardian System Actor

system.actorOf(Props[Foo], “Foo”)

Actors can form hierarchies

Page 90: Introducing Akka

Foo

Guardian System Actor

system.actorOf(Props[Foo], “Foo”)

Actors can form hierarchies

Page 91: Introducing Akka

Foo

Guardian System Actor

context.actorOf(Props[A], “A”)

Actors can form hierarchies

Page 92: Introducing Akka

A

Foo

Guardian System Actor

context.actorOf(Props[A], “A”)

Actors can form hierarchies

Page 93: Introducing Akka

A

B

BarFoo

C

BE

A

D

C

Guardian System Actor

Actors can form hierarchies

Page 94: Introducing Akka

A

B

BarFoo

C

BE

A

D

C

Guardian System Actor

Name resolution - like a file-system

Page 95: Introducing Akka

A

B

BarFoo

C

BE

A

D

C

/Foo

Guardian System Actor

Name resolution - like a file-system

Page 96: Introducing Akka

A

B

BarFoo

C

BE

A

D

C

/Foo

/Foo/A

Guardian System Actor

Name resolution - like a file-system

Page 97: Introducing Akka

A

B

BarFoo

C

BE

A

D

C

/Foo

/Foo/A

/Foo/A/B

Guardian System Actor

Name resolution - like a file-system

Page 98: Introducing Akka

A

B

BarFoo

C

BE

A

D

C

/Foo

/Foo/A

/Foo/A/B

/Foo/A/D

Guardian System Actor

Name resolution - like a file-system

Page 99: Introducing Akka

2. SEND

Page 100: Introducing Akka

2. SEND• SEND - sends a message to an Actor

Page 101: Introducing Akka

2. SEND• SEND - sends a message to an Actor

• Asynchronous and Non-blocking - Fire-forget

Page 102: Introducing Akka

2. SEND• SEND - sends a message to an Actor

• Asynchronous and Non-blocking - Fire-forget

• Everything happens Reactively

Page 103: Introducing Akka

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

Page 104: Introducing Akka

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

Page 105: Introducing Akka

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 can't do anything with it until it is triggered by a message

Page 106: Introducing Akka

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 can't do anything with it until it is triggered by a message

• EVERYTHING is asynchronous and lockless

Page 107: Introducing Akka

Throughput on a single box

+50 million messages per second

Page 108: Introducing Akka

public 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 message

Page 109: Introducing Akka

public 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 message

Send the message

Page 110: Introducing Akka

public 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"));

Full example

Page 111: Introducing Akka

case 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")

Scala version

Page 112: Introducing Akka

class SomeActor extends UntypedActor { void onReceive(Object msg) { if (msg instanceof User) { User user = (User) msg; // reply to sender getSender().tell(“Hi ” + user.name); } }}

Reply

Page 113: Introducing Akka

class SomeActor extends Actor { def receive = { case User(name) => // reply to sender sender tell (“Hi ” + name) }}

Scala version

Page 114: Introducing Akka

akka { actor { provider = akka.remote.RemoteActorRefProvider deployment { /Greeter { remote = } } }}

Just feed the ActorSystem with this configuration

Remote deployment

Page 115: Introducing Akka

akka { actor { provider = akka.remote.RemoteActorRefProvider deployment { /Greeter { remote = } } }}

Just feed the ActorSystem with this configuration

Configure a Remote Provider

Remote deployment

Page 116: Introducing Akka

akka { actor { provider = akka.remote.RemoteActorRefProvider deployment { /Greeter { remote = } } }}

Just feed the ActorSystem with this configuration

Configure a Remote Provider

For the Greeter actor

Remote deployment

Page 117: Introducing Akka

akka { actor { provider = akka.remote.RemoteActorRefProvider deployment { /Greeter { remote = } } }}

Just feed the ActorSystem with this configuration

Configure a Remote Provider

Define Remote Path

For the Greeter actor

Remote deployment

Page 118: Introducing Akka

akka { actor { provider = akka.remote.RemoteActorRefProvider deployment { /Greeter { remote = } } }}

Just feed the ActorSystem with this configuration

Configure a Remote Provider

Define Remote Path Protocol

For the Greeter actor

akka://

Remote deployment

Page 119: Introducing Akka

akka { actor { provider = akka.remote.RemoteActorRefProvider deployment { /Greeter { remote = } } }}

Just feed the ActorSystem with this configuration

Configure a Remote Provider

Define Remote Path Protocol Actor System

For the Greeter actor

akka://MySystem

Remote deployment

Page 120: Introducing Akka

akka { actor { provider = akka.remote.RemoteActorRefProvider deployment { /Greeter { remote = } } }}

Just feed the ActorSystem with this configuration

Configure a Remote Provider

Define Remote Path Protocol Actor System Hostname

For the Greeter actor

akka://MySystem@machine1

Remote deployment

Page 121: Introducing Akka

akka { actor { provider = akka.remote.RemoteActorRefProvider deployment { /Greeter { remote = } } }}

Just feed the ActorSystem with this configuration

Configure a Remote Provider

Define Remote Path Protocol Actor System Hostname Port

For the Greeter actor

akka://MySystem@machine1:2552

Remote deployment

Page 122: Introducing Akka

akka { actor { provider = akka.remote.RemoteActorRefProvider deployment { /Greeter { remote = } } }}

Just feed the ActorSystem with this configuration

Zero code changes

Configure a Remote Provider

Define Remote Path Protocol Actor System Hostname Port

For the Greeter actor

akka://MySystem@machine1:2552

Remote deployment

Page 123: Introducing Akka

3. BECOME

Page 124: Introducing Akka

3. BECOME

• BECOME - dynamically redefines Actor’s behavior

Page 125: Introducing Akka

3. BECOME

• BECOME - dynamically redefines Actor’s behavior

• Triggered reactively by receive of message

Page 126: Introducing Akka

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

Page 127: Introducing Akka

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

Page 128: Introducing Akka

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

Page 129: Introducing Akka

Why would I want to do that?

Page 130: Introducing Akka

Why would I want to do that?• Let a highly contended Actor adaptively transform

himself into an Actor Pool or a Router

Page 131: Introducing Akka

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)

Page 132: Introducing Akka

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

Page 133: Introducing Akka

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

Page 134: Introducing Akka

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

Page 135: Introducing Akka

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

Page 136: Introducing Akka

context.become(new Procedure[Object]() { void apply(Object msg) { // new body if (msg instanceof NewMessage) { NewMessage newMsg = (NewMessage)msg; ... } }});

become

Page 137: Introducing Akka

context.become(new Procedure[Object]() { void apply(Object msg) { // new body if (msg instanceof NewMessage) { NewMessage newMsg = (NewMessage)msg; ... } }});

Actor context available from within an Actor

become

Page 138: Introducing Akka

context become { // new body case NewMessage => ... }

Scala version

Page 139: Introducing Akka

Load Balancing

Page 140: Introducing Akka

Routers

val router = system.actorOf( Props[SomeActor].withRouter( RoundRobinRouter(nrOfInstances = 5)))

Scala API

Page 141: Introducing Akka

Router + Resizer

val resizer = DefaultResizer(lowerBound = 2, upperBound = 15)

val router = system.actorOf( Props[ExampleActor1].withRouter( RoundRobinRouter(resizer = Some(resizer))))

Scala API

Page 142: Introducing Akka

Failure management in Java/C/C# etc.

Page 143: Introducing Akka

• You are given a SINGLE thread of control

Failure management in Java/C/C# etc.

Page 144: Introducing Akka

• You are given a SINGLE thread of control

• If this thread blows up you are screwed

Failure management in Java/C/C# etc.

Page 145: Introducing Akka

• 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

Failure management in Java/C/C# etc.

Page 146: Introducing Akka

• 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

Failure management in Java/C/C# etc.

Page 147: Introducing Akka

• 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:

Failure management in Java/C/C# etc.

Page 148: Introducing Akka

• 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

Failure management in Java/C/C# etc.

Page 149: Introducing Akka

• 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

Failure management in Java/C/C# etc.

Page 150: Introducing Akka

• 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!!!

Failure management in Java/C/C# etc.

Page 151: Introducing Akka

4. SUPERVISE

Page 152: Introducing Akka

4. SUPERVISE

• SUPERVISE - manage another Actor’s failures

Page 153: Introducing Akka

4. SUPERVISE

• SUPERVISE - manage another Actor’s failures

• Error handling in actors is handle by letting Actors monitor (supervise) each other for failure

Page 154: Introducing Akka

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

Page 155: Introducing Akka

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

Page 156: Introducing Akka

...let’s take a standard OO application

Page 157: Introducing Akka
Page 158: Introducing Akka

Which components have critically important state

and explicit error handling?

Page 159: Introducing Akka
Page 160: Introducing Akka

Fault-tolerant onion-layered Error Kernel

Page 161: Introducing Akka

ErrorKernel

Page 162: Introducing Akka

ErrorKernel

Page 163: Introducing Akka

ErrorKernel

Page 164: Introducing Akka

ErrorKernel

Page 165: Introducing Akka

ErrorKernel

Page 166: Introducing Akka

ErrorKernel

Page 167: Introducing Akka

ErrorKernel

Node 1 Node 2

Page 168: Introducing Akka

SUPERVISE ActorEvery single actor has a

default supervisor strategy.Which is usually sufficient.But it can be overridden.

Page 169: Introducing Akka

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() { return strategy; } ActorRef worker = context.actorOf(new Props(Worker.class)); public void onReceive(Object message) throws Exception { if (message instanceof Integer) worker.forward(message); }}

SUPERVISE ActorEvery single actor has a

default supervisor strategy.Which is usually sufficient.But it can be overridden.

Page 170: Introducing Akka

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() { return strategy; } ActorRef worker = context.actorOf(new Props(Worker.class)); public void onReceive(Object message) throws Exception { if (message instanceof Integer) worker.forward(message); }}

SUPERVISE Actor

Page 171: Introducing Akka

class 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 }}

Scala version

Page 172: Introducing Akka

class 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 }}

Scala version

OneForOneStrategy

Page 173: Introducing Akka

class 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 }}

Scala version

AllForOneStrategy

Page 174: Introducing Akka

class Worker extends Actor { ... override def preRestart( reason: Throwable, message: Option[Any]) { ... // clean up before restart } override def postRestart(reason: Throwable) { ... // init after restart }}

Manage failure

Scala API

Page 175: Introducing Akka

This was

Akka 2.x

Page 176: Introducing Akka

This was

Akka 2.xWell...it’s a start...

Page 177: Introducing Akka

...we have much much more

Page 178: Introducing Akka

AMQP

Dataflow

...we have much much moreCluster FSM

Transactors

Spring

Pub/Sub

ZeroMQ

Microkernel

IOTestKit

Agents

SLF4J

Durable MailboxesEventBus

Camel

TypedActor

Extensions

HTTP/REST

Page 179: Introducing Akka

get it and learn morehttp://akka.io

http://typesafe.com

http://letitcrash.com

Page 180: Introducing Akka

EOF