SlideShare a Scribd company logo
Akka Actors And Futures


             Meetu Maltiar
         Principal Consultant
      Email: meetu@knoldus.com
        Twitter:@meetumaltiar
Akka 2.0
Akka name comes from Sami mythology is actually
     name of a goddess of wisdom and beauty.

    Akka incidentally means sister in Telugu!!
The Problem
It is way too hard to build
  => correct highly concurrent systems
  => truly scalable systems
  => self-healing, fault-tolerant systems
What is Akka?
Right abstraction with actors for concurrent, fault-tolerant
and scalable applications


For Fault-Tolerance uses “let it crash” model


Abstraction for transparent distribution for load
Introducing Actors
Actor is an entity encapsulating behavior, state and a
mailbox to receive messages

For a message received by Actor a thread is allocated to it

Then Actors behavior is applied to the message and
potentially some state is changed or messages is passed to
other Actors
Introducing Actors..
There is elasticity between message processing and addition
of new messages. New messages can be added while actor
execution is happening.

When processing of messages is completed thread is
deallocated from the actor. It can be reallocated a thread at a
later time
Akka and futures
Akka and futures
Akka and futures
Akka and futures
Create Application
import akka.actor.ActorSystem

val system =
ActorSystem("firstApp")
My First Actor
import akka.actor.{ Actor, Props }


class MyFirstActor extends Actor {
  def receive = {
    case msg => println("Hello!!")
  }
}
Create Actors
import akka.actor.{ ActorSystem, Props }


val system = ActorSystem("firstApp")
val myFirstActor =
system.actorOf(Props[MyFirstActor])


     MyFirstActor is an ActorRef
       Create a top level actor
Stop Actors
system stop myFirstActor



Also stops all actors in hierarchy
Send: !
myFirstActor ! “Hello”



      fire-forget
Ask: ?
import akka.pattern.ask


implicit val timeout = Timeout(50000 milliseconds)

val future = myActor ? "hello"


Await.result(future, timeout.duration).asInstanceOf[Int]




           Returns a Future[Any]
Reply
import akka.actor.Actor

class LongWorkingActor extends Actor {
  def receive = {
    case number: Int =>
      sender ! (“Hi I received ” + number)
  }
}
Routers
RoundRobin
Random
SmallestMailBox
BroadCast
ScatterGatherFirstCompleted
Routers...

val router =
system.actorOf(
Props[RouterWorkerActor].
withRouter(RoundRobinRouter(nrOfInstances = 5)))
Actor Path
val actorRef =
system.actorFor("akka://actorPathApp/user/pa
rent/child")

val parent = context.actorFor("..")

val sibling = context.actorFor("../sibling")


val refPath = actorRef.path
Akka Futures
A Future is a data structure

Used to retrieve of some concurrent
operation

This operation is performed by an Actor or a
dispatcher directly

The result can be accessed synchronously or
asynchronously
Execution Context
Futures need ExecutionContext to execute
callback and operations

If we have ActorSystem in scope Future will
use default dispatcher as ExecutionContext

We can use factory methods provided by
ExecutionContext companion object to wrap
Executors and ExecutorServices
Use With Actors
There are two ways to get a reply from an
Actor. First one is (myActor ! Msg)

The second way is through a Future. Using
Actors “?” method will return a Future

The simplest way to use Await method call,
though not recommended as the thread blocks
till result is obtained.
Future With Akka
              andAwait
import   akka.actor._
import   akka.pattern.ask
import   akka.util.duration._
import   akka.util.Timeout
import   akka.dispatch.Await

object FutureWithAwaitApp extends App {
  implicit val timeout = Timeout(50000 milliseconds)
  val system = ActorSystem("future")
  val echoActor = system.actorOf(Props[EchoActor])
  val future = echoActor ? "Hello World"
  val result = Await.result(future,
timeout.duration).asInstanceOf[String]
  println(result)
}
Use Futures Directly
import akka.dispatch._
import akka.util.duration._
import akka.actor.ActorSystem

object MonadicFutureApplication extends App {
  implicit val system = ActorSystem("future")

    val f1 = Future { "Hello" + "World" }
    val f2 = f1 map { x => x.length }

    val result = Await.result(f2, 1 second)
    println(result)
}
Composing Futures
object MultiMonadicFutureApplication extends App {
  implicit val system = ActorSystem("future")

    val f1 = Future { "Hello" + "World" }
    val f2 = Future { 3 }

    val f3 = f1 flatMap { x =>
      f2 map { y =>
        x.length * y
      }
    }

    val result = Await.result(f3, 1 second)
}
Code Samples

https://github.com/meetumaltiar/AkkaKnolX
References

Viktor Klang talk on Akka 2.0 at NE Scala symposium

Akka website akka.io

More Related Content

PDF
Back to the futures, actors and pipes: using Akka for large-scale data migration
PPTX
Fullstack Conference - Proxies before proxies: The hidden gems of Javascript...
PDF
3 things you must know to think reactive - Geecon Kraków 2015
PDF
Akka Futures and Akka Remoting
PDF
Concurrecny inf sharp
PDF
Actor Clustering with Docker Containers and Akka.Net in F#
PDF
The dark side of Akka and the remedy
PDF
2014-02-20 | Akka Concurrency (Vienna Scala User Group)
Back to the futures, actors and pipes: using Akka for large-scale data migration
Fullstack Conference - Proxies before proxies: The hidden gems of Javascript...
3 things you must know to think reactive - Geecon Kraków 2015
Akka Futures and Akka Remoting
Concurrecny inf sharp
Actor Clustering with Docker Containers and Akka.Net in F#
The dark side of Akka and the remedy
2014-02-20 | Akka Concurrency (Vienna Scala User Group)

What's hot (20)

PPTX
The dark side of Akka and the remedy - bp.scala meetup
PDF
Akka knolx
PDF
Akka 2.0 Reloaded
PDF
Concurrency and scalability with akka
PDF
Advanced akka features
PDF
Actor Model Akka Framework
PPTX
Introduction to Akka - Atlanta Java Users Group
PDF
2018 05-16 Evolving Technologies: React, Babel & Webpack
PDF
Actor based approach in practice for Swift developers
PDF
Phoenix demysitify, with fun
PDF
Sane Sharding with Akka Cluster
PDF
Django for IoT: From hackathon to production (DjangoCon US)
PPTX
Scalamen and OT
PDF
Higher Order Components and Render Props
PDF
Testing akka-actors
PPTX
Alteryx SDK
PDF
Building a chatbot – step by step
PDF
Writing Asynchronous Programs with Scala & Akka
PDF
The internet of (lego) trains
PDF
Akka persistence == event sourcing in 30 minutes
The dark side of Akka and the remedy - bp.scala meetup
Akka knolx
Akka 2.0 Reloaded
Concurrency and scalability with akka
Advanced akka features
Actor Model Akka Framework
Introduction to Akka - Atlanta Java Users Group
2018 05-16 Evolving Technologies: React, Babel & Webpack
Actor based approach in practice for Swift developers
Phoenix demysitify, with fun
Sane Sharding with Akka Cluster
Django for IoT: From hackathon to production (DjangoCon US)
Scalamen and OT
Higher Order Components and Render Props
Testing akka-actors
Alteryx SDK
Building a chatbot – step by step
Writing Asynchronous Programs with Scala & Akka
The internet of (lego) trains
Akka persistence == event sourcing in 30 minutes
Ad

Similar to Akka and futures (20)

PPTX
Nairobi JVM meetup : Introduction to akka
 
PDF
Introducing Akka
PDF
Building Massively Scalable application with Akka 2.0
PDF
Akka-intro-training-public.pdf
PDF
Reactive programming with akka
PPTX
Akka Actors
KEY
Introduction to Actor Model and Akka
PDF
Effective Akka v2
PDF
PDF
Introduction to Actor Model and Akka
PDF
Message-based communication patterns in distributed Akka applications
PPTX
Akka framework
PDF
Basics of Akka
PDF
Akka Actors: an Introduction
PDF
Introduction to Akka
PPTX
Actor-based concurrency and Akka Fundamentals
PDF
Build Cloud Applications with Akka and Heroku
PDF
Reactive programming with akka
PDF
Reactive Programming in Akka
KEY
Akka london scala_user_group
Nairobi JVM meetup : Introduction to akka
 
Introducing Akka
Building Massively Scalable application with Akka 2.0
Akka-intro-training-public.pdf
Reactive programming with akka
Akka Actors
Introduction to Actor Model and Akka
Effective Akka v2
Introduction to Actor Model and Akka
Message-based communication patterns in distributed Akka applications
Akka framework
Basics of Akka
Akka Actors: an Introduction
Introduction to Akka
Actor-based concurrency and Akka Fundamentals
Build Cloud Applications with Akka and Heroku
Reactive programming with akka
Reactive Programming in Akka
Akka london scala_user_group
Ad

More from Knoldus Inc. (20)

PPTX
Angular Hydration Presentation (FrontEnd)
PPTX
Optimizing Test Execution: Heuristic Algorithm for Self-Healing
PPTX
Self-Healing Test Automation Framework - Healenium
PPTX
Kanban Metrics Presentation (Project Management)
PPTX
Java 17 features and implementation.pptx
PPTX
Chaos Mesh Introducing Chaos in Kubernetes
PPTX
GraalVM - A Step Ahead of JVM Presentation
PPTX
Nomad by HashiCorp Presentation (DevOps)
PPTX
Nomad by HashiCorp Presentation (DevOps)
PPTX
DAPR - Distributed Application Runtime Presentation
PPTX
Introduction to Azure Virtual WAN Presentation
PPTX
Introduction to Argo Rollouts Presentation
PPTX
Intro to Azure Container App Presentation
PPTX
Insights Unveiled Test Reporting and Observability Excellence
PPTX
Introduction to Splunk Presentation (DevOps)
PPTX
Code Camp - Data Profiling and Quality Analysis Framework
PPTX
AWS: Messaging Services in AWS Presentation
PPTX
Amazon Cognito: A Primer on Authentication and Authorization
PPTX
ZIO Http A Functional Approach to Scalable and Type-Safe Web Development
PPTX
Managing State & HTTP Requests In Ionic.
Angular Hydration Presentation (FrontEnd)
Optimizing Test Execution: Heuristic Algorithm for Self-Healing
Self-Healing Test Automation Framework - Healenium
Kanban Metrics Presentation (Project Management)
Java 17 features and implementation.pptx
Chaos Mesh Introducing Chaos in Kubernetes
GraalVM - A Step Ahead of JVM Presentation
Nomad by HashiCorp Presentation (DevOps)
Nomad by HashiCorp Presentation (DevOps)
DAPR - Distributed Application Runtime Presentation
Introduction to Azure Virtual WAN Presentation
Introduction to Argo Rollouts Presentation
Intro to Azure Container App Presentation
Insights Unveiled Test Reporting and Observability Excellence
Introduction to Splunk Presentation (DevOps)
Code Camp - Data Profiling and Quality Analysis Framework
AWS: Messaging Services in AWS Presentation
Amazon Cognito: A Primer on Authentication and Authorization
ZIO Http A Functional Approach to Scalable and Type-Safe Web Development
Managing State & HTTP Requests In Ionic.

Akka and futures

  • 1. Akka Actors And Futures Meetu Maltiar Principal Consultant Email: [email protected] Twitter:@meetumaltiar
  • 2. Akka 2.0 Akka name comes from Sami mythology is actually name of a goddess of wisdom and beauty. Akka incidentally means sister in Telugu!!
  • 3. The Problem It is way too hard to build => correct highly concurrent systems => truly scalable systems => self-healing, fault-tolerant systems
  • 4. What is Akka? Right abstraction with actors for concurrent, fault-tolerant and scalable applications For Fault-Tolerance uses “let it crash” model Abstraction for transparent distribution for load
  • 5. Introducing Actors Actor is an entity encapsulating behavior, state and a mailbox to receive messages For a message received by Actor a thread is allocated to it Then Actors behavior is applied to the message and potentially some state is changed or messages is passed to other Actors
  • 6. Introducing Actors.. There is elasticity between message processing and addition of new messages. New messages can be added while actor execution is happening. When processing of messages is completed thread is deallocated from the actor. It can be reallocated a thread at a later time
  • 11. Create Application import akka.actor.ActorSystem val system = ActorSystem("firstApp")
  • 12. My First Actor import akka.actor.{ Actor, Props } class MyFirstActor extends Actor { def receive = { case msg => println("Hello!!") } }
  • 13. Create Actors import akka.actor.{ ActorSystem, Props } val system = ActorSystem("firstApp") val myFirstActor = system.actorOf(Props[MyFirstActor]) MyFirstActor is an ActorRef Create a top level actor
  • 14. Stop Actors system stop myFirstActor Also stops all actors in hierarchy
  • 15. Send: ! myFirstActor ! “Hello” fire-forget
  • 16. Ask: ? import akka.pattern.ask implicit val timeout = Timeout(50000 milliseconds) val future = myActor ? "hello" Await.result(future, timeout.duration).asInstanceOf[Int] Returns a Future[Any]
  • 17. Reply import akka.actor.Actor class LongWorkingActor extends Actor { def receive = { case number: Int => sender ! (“Hi I received ” + number) } }
  • 20. Actor Path val actorRef = system.actorFor("akka://actorPathApp/user/pa rent/child") val parent = context.actorFor("..") val sibling = context.actorFor("../sibling") val refPath = actorRef.path
  • 21. Akka Futures A Future is a data structure Used to retrieve of some concurrent operation This operation is performed by an Actor or a dispatcher directly The result can be accessed synchronously or asynchronously
  • 22. Execution Context Futures need ExecutionContext to execute callback and operations If we have ActorSystem in scope Future will use default dispatcher as ExecutionContext We can use factory methods provided by ExecutionContext companion object to wrap Executors and ExecutorServices
  • 23. Use With Actors There are two ways to get a reply from an Actor. First one is (myActor ! Msg) The second way is through a Future. Using Actors “?” method will return a Future The simplest way to use Await method call, though not recommended as the thread blocks till result is obtained.
  • 24. Future With Akka andAwait import akka.actor._ import akka.pattern.ask import akka.util.duration._ import akka.util.Timeout import akka.dispatch.Await object FutureWithAwaitApp extends App { implicit val timeout = Timeout(50000 milliseconds) val system = ActorSystem("future") val echoActor = system.actorOf(Props[EchoActor]) val future = echoActor ? "Hello World" val result = Await.result(future, timeout.duration).asInstanceOf[String] println(result) }
  • 25. Use Futures Directly import akka.dispatch._ import akka.util.duration._ import akka.actor.ActorSystem object MonadicFutureApplication extends App { implicit val system = ActorSystem("future") val f1 = Future { "Hello" + "World" } val f2 = f1 map { x => x.length } val result = Await.result(f2, 1 second) println(result) }
  • 26. Composing Futures object MultiMonadicFutureApplication extends App { implicit val system = ActorSystem("future") val f1 = Future { "Hello" + "World" } val f2 = Future { 3 } val f3 = f1 flatMap { x => f2 map { y => x.length * y } } val result = Await.result(f3, 1 second) }
  • 28. References Viktor Klang talk on Akka 2.0 at NE Scala symposium Akka website akka.io