SlideShare a Scribd company logo
1 of 28
Download to read offline
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
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

What's hot

The dark side of Akka and the remedy - bp.scala meetup
The dark side of Akka and the remedy - bp.scala meetupThe dark side of Akka and the remedy - bp.scala meetup
The dark side of Akka and the remedy - bp.scala meetupkrivachy
 
Concurrency and scalability with akka
Concurrency and scalability  with akkaConcurrency and scalability  with akka
Concurrency and scalability with akkaBardia Heydari
 
Advanced akka features
Advanced akka featuresAdvanced akka features
Advanced akka featuresGrzegorz Duda
 
Introduction to Akka - Atlanta Java Users Group
Introduction to Akka - Atlanta Java Users GroupIntroduction to Akka - Atlanta Java Users Group
Introduction to Akka - Atlanta Java Users GroupRoy Russo
 
2018 05-16 Evolving Technologies: React, Babel & Webpack
2018 05-16 Evolving Technologies: React, Babel & Webpack2018 05-16 Evolving Technologies: React, Babel & Webpack
2018 05-16 Evolving Technologies: React, Babel & WebpackCodifly
 
Actor based approach in practice for Swift developers
Actor based approach in practice for Swift developersActor based approach in practice for Swift developers
Actor based approach in practice for Swift developersBartosz Polaczyk
 
Phoenix demysitify, with fun
Phoenix demysitify, with funPhoenix demysitify, with fun
Phoenix demysitify, with funTai An Su
 
Sane Sharding with Akka Cluster
Sane Sharding with Akka ClusterSane Sharding with Akka Cluster
Sane Sharding with Akka Clustermiciek
 
Django for IoT: From hackathon to production (DjangoCon US)
Django for IoT: From hackathon to production (DjangoCon US)Django for IoT: From hackathon to production (DjangoCon US)
Django for IoT: From hackathon to production (DjangoCon US)Anna Schneider
 
Scalamen and OT
Scalamen and OTScalamen and OT
Scalamen and OTgetch123
 
Higher Order Components and Render Props
Higher Order Components and Render PropsHigher Order Components and Render Props
Higher Order Components and Render PropsNitish Phanse
 
Testing akka-actors
Testing akka-actorsTesting akka-actors
Testing akka-actorsKnoldus Inc.
 
Writing Asynchronous Programs with Scala & Akka
Writing Asynchronous Programs with Scala & AkkaWriting Asynchronous Programs with Scala & Akka
Writing Asynchronous Programs with Scala & AkkaYardena Meymann
 
The internet of (lego) trains
The internet of (lego) trainsThe internet of (lego) trains
The internet of (lego) trainsGrzegorz Duda
 
Akka persistence == event sourcing in 30 minutes
Akka persistence == event sourcing in 30 minutesAkka persistence == event sourcing in 30 minutes
Akka persistence == event sourcing in 30 minutesKonrad Malawski
 

What's hot (20)

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

Similar to Akka and futures

Akka Actors: an Introduction
Akka Actors: an IntroductionAkka Actors: an Introduction
Akka Actors: an IntroductionRoberto Casadei
 
Nairobi JVM meetup : Introduction to akka
Nairobi JVM meetup : Introduction to akkaNairobi JVM meetup : Introduction to akka
Nairobi JVM meetup : Introduction to akkaAD_
 
Message-based communication patterns in distributed Akka applications
Message-based communication patterns in distributed Akka applicationsMessage-based communication patterns in distributed Akka applications
Message-based communication patterns in distributed Akka applicationsAndrii Lashchenko
 
Building Massively Scalable application with Akka 2.0
Building Massively Scalable application with Akka 2.0Building Massively Scalable application with Akka 2.0
Building Massively Scalable application with Akka 2.0Knoldus Inc.
 
Scalaz 8 vs Akka Actors
Scalaz 8 vs Akka ActorsScalaz 8 vs Akka Actors
Scalaz 8 vs Akka ActorsJohn De Goes
 
Reactive Programming in .Net - actorbased computing with Akka.Net
Reactive Programming in .Net - actorbased computing with Akka.NetReactive Programming in .Net - actorbased computing with Akka.Net
Reactive Programming in .Net - actorbased computing with Akka.NetSören Stelzer
 
Akka lsug skills matter
Akka lsug skills matterAkka lsug skills matter
Akka lsug skills matterSkills Matter
 
Scaling Web Apps with Akka
Scaling Web Apps with AkkaScaling Web Apps with Akka
Scaling Web Apps with AkkaMaciej Matyjas
 
GPars (Groovy Parallel Systems)
GPars (Groovy Parallel Systems)GPars (Groovy Parallel Systems)
GPars (Groovy Parallel Systems)Gagan Agrawal
 
Akka london scala_user_group
Akka london scala_user_groupAkka london scala_user_group
Akka london scala_user_groupSkills Matter
 
Reactive programming with akka
Reactive programming with akkaReactive programming with akka
Reactive programming with akkaWebdesign Factory
 
Building Stateful Microservices With Akka
Building Stateful Microservices With AkkaBuilding Stateful Microservices With Akka
Building Stateful Microservices With AkkaYaroslav Tkachenko
 
Introduction to Actor Model and Akka
Introduction to Actor Model and AkkaIntroduction to Actor Model and Akka
Introduction to Actor Model and AkkaYung-Lin Ho
 
Developing a Real-time Engine with Akka, Cassandra, and Spray
Developing a Real-time Engine with Akka, Cassandra, and SprayDeveloping a Real-time Engine with Akka, Cassandra, and Spray
Developing a Real-time Engine with Akka, Cassandra, and SprayJacob Park
 
Activator and Reactive at Play NYC meetup
Activator and Reactive at Play NYC meetupActivator and Reactive at Play NYC meetup
Activator and Reactive at Play NYC meetupHenrik Engström
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMMario Fusco
 
From Elixir to Akka (and back) - ElixirConf Mx 2017
From Elixir to Akka (and back) - ElixirConf Mx 2017From Elixir to Akka (and back) - ElixirConf Mx 2017
From Elixir to Akka (and back) - ElixirConf Mx 2017Agustin Ramos
 

Similar to Akka and futures (20)

Akka Actors: an Introduction
Akka Actors: an IntroductionAkka Actors: an Introduction
Akka Actors: an Introduction
 
Nairobi JVM meetup : Introduction to akka
Nairobi JVM meetup : Introduction to akkaNairobi JVM meetup : Introduction to akka
Nairobi JVM meetup : Introduction to akka
 
Introducing Akka
Introducing AkkaIntroducing Akka
Introducing Akka
 
Message-based communication patterns in distributed Akka applications
Message-based communication patterns in distributed Akka applicationsMessage-based communication patterns in distributed Akka applications
Message-based communication patterns in distributed Akka applications
 
Building Massively Scalable application with Akka 2.0
Building Massively Scalable application with Akka 2.0Building Massively Scalable application with Akka 2.0
Building Massively Scalable application with Akka 2.0
 
Scalaz 8 vs Akka Actors
Scalaz 8 vs Akka ActorsScalaz 8 vs Akka Actors
Scalaz 8 vs Akka Actors
 
Reactive Programming in .Net - actorbased computing with Akka.Net
Reactive Programming in .Net - actorbased computing with Akka.NetReactive Programming in .Net - actorbased computing with Akka.Net
Reactive Programming in .Net - actorbased computing with Akka.Net
 
Akka lsug skills matter
Akka lsug skills matterAkka lsug skills matter
Akka lsug skills matter
 
Scaling Web Apps with Akka
Scaling Web Apps with AkkaScaling Web Apps with Akka
Scaling Web Apps with Akka
 
GPars (Groovy Parallel Systems)
GPars (Groovy Parallel Systems)GPars (Groovy Parallel Systems)
GPars (Groovy Parallel Systems)
 
Akka london scala_user_group
Akka london scala_user_groupAkka london scala_user_group
Akka london scala_user_group
 
Reactive programming with akka
Reactive programming with akkaReactive programming with akka
Reactive programming with akka
 
Building Stateful Microservices With Akka
Building Stateful Microservices With AkkaBuilding Stateful Microservices With Akka
Building Stateful Microservices With Akka
 
Introduction to Actor Model and Akka
Introduction to Actor Model and AkkaIntroduction to Actor Model and Akka
Introduction to Actor Model and Akka
 
Developing a Real-time Engine with Akka, Cassandra, and Spray
Developing a Real-time Engine with Akka, Cassandra, and SprayDeveloping a Real-time Engine with Akka, Cassandra, and Spray
Developing a Real-time Engine with Akka, Cassandra, and Spray
 
Activator and Reactive at Play NYC meetup
Activator and Reactive at Play NYC meetupActivator and Reactive at Play NYC meetup
Activator and Reactive at Play NYC meetup
 
.NET F# Events
.NET F# Events.NET F# Events
.NET F# Events
 
Akka Testkit Patterns
Akka Testkit PatternsAkka Testkit Patterns
Akka Testkit Patterns
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
 
From Elixir to Akka (and back) - ElixirConf Mx 2017
From Elixir to Akka (and back) - ElixirConf Mx 2017From Elixir to Akka (and back) - ElixirConf Mx 2017
From Elixir to Akka (and back) - ElixirConf Mx 2017
 

More from Knoldus Inc.

Supply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptxSupply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptxKnoldus Inc.
 
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingMastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingKnoldus Inc.
 
Akka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionAkka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionKnoldus Inc.
 
Entity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxEntity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxKnoldus Inc.
 
Introduction to Redis and its features.pptx
Introduction to Redis and its features.pptxIntroduction to Redis and its features.pptx
Introduction to Redis and its features.pptxKnoldus Inc.
 
GraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfGraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfKnoldus Inc.
 
NuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxNuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxKnoldus Inc.
 
Data Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingData Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingKnoldus Inc.
 
K8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesK8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesKnoldus Inc.
 
Introduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptxIntroduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptxKnoldus Inc.
 
Robusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxRobusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxKnoldus Inc.
 
Optimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxOptimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxKnoldus Inc.
 
Azure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxAzure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxKnoldus Inc.
 
CQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxCQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxKnoldus Inc.
 
ETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationKnoldus Inc.
 
Scripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationScripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationKnoldus Inc.
 
Getting started with dotnet core Web APIs
Getting started with dotnet core Web APIsGetting started with dotnet core Web APIs
Getting started with dotnet core Web APIsKnoldus Inc.
 
Introduction To Rust part II Presentation
Introduction To Rust part II PresentationIntroduction To Rust part II Presentation
Introduction To Rust part II PresentationKnoldus Inc.
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Configuring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAConfiguring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAKnoldus Inc.
 

More from Knoldus Inc. (20)

Supply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptxSupply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptx
 
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingMastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
 
Akka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionAkka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On Introduction
 
Entity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxEntity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptx
 
Introduction to Redis and its features.pptx
Introduction to Redis and its features.pptxIntroduction to Redis and its features.pptx
Introduction to Redis and its features.pptx
 
GraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfGraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdf
 
NuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxNuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptx
 
Data Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingData Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable Testing
 
K8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesK8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose Kubernetes
 
Introduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptxIntroduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptx
 
Robusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxRobusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptx
 
Optimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxOptimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptx
 
Azure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxAzure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptx
 
CQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxCQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptx
 
ETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake Presentation
 
Scripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationScripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics Presentation
 
Getting started with dotnet core Web APIs
Getting started with dotnet core Web APIsGetting started with dotnet core Web APIs
Getting started with dotnet core Web APIs
 
Introduction To Rust part II Presentation
Introduction To Rust part II PresentationIntroduction To Rust part II Presentation
Introduction To Rust part II Presentation
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Configuring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAConfiguring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRA
 

Akka and futures

  • 1. Akka Actors And Futures Meetu Maltiar Principal Consultant Email: meetu@knoldus.com 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
  • 7.
  • 8.
  • 9.
  • 10.
  • 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