SlideShare a Scribd company logo
Introduction to
Concurrent programming
with
Akka Actors
https://github.com/shashankgowdal/introduction-to-concurrentprogrammin
g-with-akka
● Shashank L
● Senior Software engineer at Tellius
● Part time big data consultant and trainer
at datamantra.io
● www.shashankgowda.com
Concurrency
● Concurrency is the decomposability property of a
program, algorithm, or problem into order-independent or
partially-ordered components or units
● Structure a program by breaking it into pieces that can be
executed independently
● Co ordinating the execution of independent pieces
Concurrency and parallelism
● Concurrency is dealing with more than one thing at once
● Parallelism is doing more than one thing at once
Given tasks T1 and T2
T1 may be executed and finished before T2 or vice versa
(serial and sequential)
T1 and T2 may be executed alternately
(serial and concurrent)
T1 and T2 may be executed simultaneously at the same instant of time
(parallel and concurrent)
Concurrency is not parallelism
● Queues can be thought of
processed/threads
● Vending machine is
processor core
Moore’s law
The number of transistors on a chip doubles approximately
every 2 years.
~ Gordon Moore, 1965
Free performance lunch
● Over 30 years till 2000, performance gains were in 3
areas
○ Clock speed
○ Execution optimization
○ Caching
Old applications have always run significantly faster
even without being recompiled
Moore’s law
● Early 2000
○ Chips got big, transistors were added aggressively
○ Clock cycle was almost unchanged
○ Heat dissipation issues
○ Power consumption
○ Current leakage
Moore’s law
Birth of Multicore processors
● Multi-core processors
● Handle multiple operations in parallel
● CPU speeds are not increasing drastically anytime soon
● No free performance lunch without significant redesign
● Performance gains in new chips will be fueled by three main
approaches
○ Hyperthreading
○ Multicore
○ cache
Free performance lunch is over
● Concurrency revolution
● Build multi core aware applications
● Operate in concurrent fashion
● Scale horizontally
Types of Concurrency
● Shared state concurrency
● Software transactional concurrency
● Message passing concurrency
Shared state concurrency
● Shared mutability
● Memory blocks can be access simultaneously by multiple
programs
● Race condition
● Dead locks
● Blocking calls
com.shashank.akka.basic.ThreadUnsafeBuffer
Software transactional memory
● Shared, managed mutability
● Objects can be mutated only within a transaction
● STM keeps track of changes made in a particular
● Once transaction is completed, it validates and commits the
results
● Validation fails when others have committed the result
● Transaction will be repeated with the updated value.
Message passing concurrency
● Isolated mutability
● Mutable objects are isolated from the threads
● Threads will not be able to directly access the objects
● Access to the mutable objects is done through messages
● Sending message can be asynchronous and nonblocking
Joe Armstrong’s words
The world is concurrent. It is parallel. Pure message-passing
concurrency is what we do all the time.
Imagine a group of people. They have no shared state.
I have my private memory (in my head) and you have yours. It is NOT
shared. We communicate by passing messages (sound and light
waves). We update our private state based on the reception of these
messages.
That’s Concurrency Oriented Programming in a nutshell.
Actors
● From a 1973 paper, written by Carl Hewitt
● First major adoption was done by Ericsson in 80s
○ Invented Erlang and open sourced in 90s
○ Built a distributed, concurrent, and fault-tolerant telcom
system which has 99.9999999% uptime
● Implements Message-Passing or Isolated mutability based
concurrency
Actor model
● Share Nothing
○ No need to synchronize.
● Isolated. Lightweight event-based Processes
○ ~ 6.5m on 4GB RAM
● Communicate through Messages
○ Asynchronous and Nonblocking
○ Messages are immutable
● Each actor has a mailbox (message queue)
● Scalable and fast
When an Actor receives messages
● Creates new actors
● Send message to other actors/self
● Designate how it should handle the next
message
Akka
● Founded by Jonas Boner and now part of Typesafe stack
● Actor implementation on JVM - Scala
○ Java API and Scala API
● Provides a framework to create & manage actors
● Backed by JVM Thread model
● Akka provides a mailbox for each actor
○ in-memory queue to stage messages
● Clients can send messages synchronously or
asynchronously
● Actor receives messages and respond to clients
Actor System
● Actors are created within this context
● Fundamental unit that embodies:
Processing, storage and communication
● Manage shared facilities:
scheduling, logging, configuration etc
● Can have many per JVM with different configs
● Can contain millions of actors
ACTOR OPERATIONS
DEFINE
class LoggerActor extends Actor {
def receive = {
case x:String => println(x)
case _ => println("huh?")
}
}
CREATE
val system = ActorSystem("LogSystem")
val loggerActor = system.actorOf(
Props[LoggerActor],
name = "loggeractor")
SEND
● Fire and forget
○ Async
○ No expected reply
○ ! or tell()
● Send and Receive
○ Async
○ Expects reply (Future)
○ ? or ask()
SEND - Fire and forget
//No need to return anything in the receive method
def receive = {
case x:Int => println(x)
}
//Send the message and don’t wait for the reply
actorRef ! (100)
com.shashank.akka.basic.SimpleActor
SEND - Send and receive
//Use the sender method to get the actorRef of the sender
def receive = {
case "hello" =>
sender() ! ("hello how are you?")
}
//Send the message and get a future back, we can wait for that future to be successful to get
the result
val responseFuture = bufferActor ? ("hello")
responseFuture onSuccess{
case response => println(response)
}
com.shashank.akka.basic.ThreadSafeBuffer
ActorRef
ActorRef Mailbox
Actor
Instance
Points to Actor
Delivers to Mailbox
Mailbox
ActorRef Mailbox
Actor
Instance
Invokes Actor Instance with Message
Runs on dispatcher - abstracts threading
ActorInstance
ActorRef Mailbox
Actor
Instance
Your code here
BECOME
● Dynamically redefines actor behaviour
● Reactively triggered by message
● Like changing an interface or implementation on-the-fly
com.shashank.akka.basic.ThreadSafeBufferWithLimit
How error handling is done in Java
● 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
● Errors do not propagate between threads
● This leads to Defensive programming with
○ Error handling tangled with business logic
○ Error handling scattered all over the code
SUPERVISE
● Manage another actor’s failure
● Supervisor receives notification
and it can react upon failure
● Every actor has a default
supervisor strategy
○ Can be overridden
SUPERVISE
● On Failure, Supervisor decides what happens next
○ Resume child and keep the internal state
○ Restart child and wipe the internal state
○ Stop child permanently
○ Stop itself and escalate the error
● OneForOneStrategy affects only failed child
● AllForOneStrategy affects all the children
com.shashank.akka.supervision.BasicSupervision
SUPERVISE - OneForOneStrategy
SUPERVISE - AllForOneStrategy
Actor can form a hierarchy
Actor can form a hierarchy
Name resolution - like a file system
Stopping Actors
//Shutting down the Actor System
system.shutdown()
//Sending PoisonPill message
actorRef ? (PoisonPill)
//Shutting the actor from inside the actor
context.stop(self)
//Shutting another actor from inside the actor
context.stop(actorRef)
com.shashank.akka.basic.ShuttingDown
Message delivery
● At most once - No guaranteed delivery
● Cheapest
● Highest performance
● Least implementation overhead
● It can be done in a fire-and-forget fashion without keeping
state at the sending end or in the transport mechanism
● At least once - Akka persistence
Message ordering
● Message ordering per sender-receiver pair
Dispatcher
● Controls and coordinates the message dispatching to the
actors
● Make sure that the resources are optimized and messages
are processed as fast as possible
● Dispatch policies that can be customized(number of cores or
memory available)
Dispatcher
● Runways - Threads
● Airlines - Mailboxes
● ATC - Dispatcher or
Dispatch policy
Dispatcher
Dispatcher and Mailboxes
Types of dispatchers
● Dispatcher
● Pinned dispatcher
● Balancing dispatcher
● Calling thread dispatcher
Mailbox implementations
● Unbounded mailbox
● Bounded mailbox
● Unbounded priority mailbox
● Bounded priority mailbox
● Entity that directs the message from source to the destination actor
● Router is also a type of actor
● Does not make use of the store-and-forward mechanism
● Routers dispatch the incoming messages directly to the destination
actor’s mailboxes
system.actorOf(Props[MyActor].withRouter(RoundRobinRouter(nrOfInstances = 5)))
Routers
● Round robin router
It routes the incoming messages in a circular order to all its routees
● Random router
It randomly selects a routee and routes the message to the same
● Smallest mailbox router
It identifies the actor with the least number of messages in its mailbox and routes the
message to the same
● Broadcast router
It forwards the same message to all the routees
● Scatter gather first completed router
It forwards the message to all its routees as a future, then whichever routee actor responds
back, it takes the results and sends them back to the caller
com.shashank.akka.basic.Router
Types of Routers
def preStart(): Unit = ()
def postStop(): Unit = ()
def preRestart(reason: Throwable, message: Option[Any]): Unit = {
context.children foreach { child ⇒
context.stop(child)
}
postStop()
}
def postRestart(reason: Throwable): Unit = {
preStart()
}
Actor API
● A path is a place that can be occupied by a living actor
● When actorOf() is called it assigns an incarnation of the
actor described by the passed Props to the given path
● An ActorRef always represents an incarnation (path and
UID) not just a given path. Another actor created later with
the same name will have a different ActorRef
// will look up this absolute path
context.actorSelection("/user/serviceA/aggregator")
// will look up sibling beneath same supervisor
context.actorSelection("../joe")
Actor Path
Actor life-cycle
● Consists of 2 parts
○ A public interface
○ An implementation
● Similar to Interface and implements in Java, Traits in
Scala
● TypedActors have a static contract
● Some features like become is not available
● Bridging between actor systems (the “inside”) and
non-actor code (the “outside”)
Typed actors
def squareDontCare(i: Int): Unit //fire-forget
def square(i: Int): Future[Int] //non-blocking send-request-reply
def squareNowPlease(i: Int): Option[Int] //blocking send-request-reply
def squareNow(i: Int): Int //blocking send-request-reply
@throws(classOf[Exception]) //declare it or you will get an UndeclaredThrowableException
def squareTry(i: Int): Int //blocking send-request-reply with possible exception
//Creating an actorRef of a TypedActor
val mySquarer: Squarer = TypedActor(system).typedActorOf(TypedProps[SquarerImpl]())
com.shashank.akka.basic.TypedActorExample
Typed actors
● Dedicated module akka-testkit for supporting tests
● Testing isolated pieces of code without involving the actor
model, meaning without multiple threads
● Testing (multiple) encapsulated actors including
multi-threaded scheduling
● Integration with ScalaTest to write more readable
assertions
com.shashank.akka.supervision.SupervisorTestSpec
Actor TestKit
● All configuration for Akka is held within instances of ActorSystem
● ActorSystem is the only consumer of configuration information
● Parse the configuration file
val config =
ConfigFactory.parseFile(new File("src/main/resources/router/application.conf"))
val system = ActorSystem("NameOfActorSystem", config)
● Read the configuration files automatically from ClassLoader
val config = ConfigFactory.defaultReference()
val system = ActorSystem("NameOfActorSystem", config)
● Parse all application.conf, application.json and application.properties
● akka.log-config-on-start
Configuration - TypeSafe config
● Distributed by default
● Messages should be and are serializable
● ActorRefs are serializable
● Probability of the message reaching is higher than local
JVM
● No separate remoting layer in Akka. Purely driven by
config
● Communication between involved system is symmetric
● Not possible to create pure client-server setups
Remote Actors
Remote Actors
com.shashank.akka.remote
In different scenarios Actors can be alternatives for:
● A thread
● An object instance or component
● A callback or listener
● A singleton or service
● A router, load-balancer or pool
● An out-of-service process
● A Finite State machine (FSM)
What can I use Actors for?
● http://doc.akka.io/docs/akka/2.4/scala
● http://blog.madhukaraphatak.com/simple-akka-remote-example/
● https://www.youtube.com/watch?v=W_l57iyn4mU
Programming with Actors by Venkat
● https://www.slideshare.net/jboner/introducing-akka
● https://www.slideshare.net/RoyRusso1/introduction-to-akka-atlanta-ja
va-users-group
● https://blog.golang.org/concurrency-is-not-parallelism
References

More Related Content

What's hot

Exploratory Data Analysis in Spark
Exploratory Data Analysis in SparkExploratory Data Analysis in Spark
Exploratory Data Analysis in Spark
datamantra
 
Understanding Implicits in Scala
Understanding Implicits in ScalaUnderstanding Implicits in Scala
Understanding Implicits in Scala
datamantra
 
Migrating to Spark 2.0 - Part 2
Migrating to Spark 2.0 - Part 2Migrating to Spark 2.0 - Part 2
Migrating to Spark 2.0 - Part 2
datamantra
 
Building end to end streaming application on Spark
Building end to end streaming application on SparkBuilding end to end streaming application on Spark
Building end to end streaming application on Spark
datamantra
 
Productionalizing Spark ML
Productionalizing Spark MLProductionalizing Spark ML
Productionalizing Spark ML
datamantra
 
Improving Mobile Payments With Real time Spark
Improving Mobile Payments With Real time SparkImproving Mobile Payments With Real time Spark
Improving Mobile Payments With Real time Spark
datamantra
 
A Tool For Big Data Analysis using Apache Spark
A Tool For Big Data Analysis using Apache SparkA Tool For Big Data Analysis using Apache Spark
A Tool For Big Data Analysis using Apache Spark
datamantra
 
Productionalizing a spark application
Productionalizing a spark applicationProductionalizing a spark application
Productionalizing a spark application
datamantra
 
Structured Streaming with Kafka
Structured Streaming with KafkaStructured Streaming with Kafka
Structured Streaming with Kafka
datamantra
 
Introduction to Spark 2.0 Dataset API
Introduction to Spark 2.0 Dataset APIIntroduction to Spark 2.0 Dataset API
Introduction to Spark 2.0 Dataset API
datamantra
 
Core Services behind Spark Job Execution
Core Services behind Spark Job ExecutionCore Services behind Spark Job Execution
Core Services behind Spark Job Execution
datamantra
 
Introduction to Flink Streaming
Introduction to Flink StreamingIntroduction to Flink Streaming
Introduction to Flink Streaming
datamantra
 
Multi Source Data Analysis using Spark and Tellius
Multi Source Data Analysis using Spark and TelliusMulti Source Data Analysis using Spark and Tellius
Multi Source Data Analysis using Spark and Tellius
datamantra
 
Understanding time in structured streaming
Understanding time in structured streamingUnderstanding time in structured streaming
Understanding time in structured streaming
datamantra
 
Building real time Data Pipeline using Spark Streaming
Building real time Data Pipeline using Spark StreamingBuilding real time Data Pipeline using Spark Streaming
Building real time Data Pipeline using Spark Streaming
datamantra
 
Introduction to dataset
Introduction to datasetIntroduction to dataset
Introduction to dataset
datamantra
 
Building scalable rest service using Akka HTTP
Building scalable rest service using Akka HTTPBuilding scalable rest service using Akka HTTP
Building scalable rest service using Akka HTTP
datamantra
 
Anatomy of Data Source API : A deep dive into Spark Data source API
Anatomy of Data Source API : A deep dive into Spark Data source APIAnatomy of Data Source API : A deep dive into Spark Data source API
Anatomy of Data Source API : A deep dive into Spark Data source API
datamantra
 
Introduction to Structured Streaming
Introduction to Structured StreamingIntroduction to Structured Streaming
Introduction to Structured Streaming
datamantra
 
Spark architecture
Spark architectureSpark architecture
Spark architecture
datamantra
 

What's hot (20)

Exploratory Data Analysis in Spark
Exploratory Data Analysis in SparkExploratory Data Analysis in Spark
Exploratory Data Analysis in Spark
 
Understanding Implicits in Scala
Understanding Implicits in ScalaUnderstanding Implicits in Scala
Understanding Implicits in Scala
 
Migrating to Spark 2.0 - Part 2
Migrating to Spark 2.0 - Part 2Migrating to Spark 2.0 - Part 2
Migrating to Spark 2.0 - Part 2
 
Building end to end streaming application on Spark
Building end to end streaming application on SparkBuilding end to end streaming application on Spark
Building end to end streaming application on Spark
 
Productionalizing Spark ML
Productionalizing Spark MLProductionalizing Spark ML
Productionalizing Spark ML
 
Improving Mobile Payments With Real time Spark
Improving Mobile Payments With Real time SparkImproving Mobile Payments With Real time Spark
Improving Mobile Payments With Real time Spark
 
A Tool For Big Data Analysis using Apache Spark
A Tool For Big Data Analysis using Apache SparkA Tool For Big Data Analysis using Apache Spark
A Tool For Big Data Analysis using Apache Spark
 
Productionalizing a spark application
Productionalizing a spark applicationProductionalizing a spark application
Productionalizing a spark application
 
Structured Streaming with Kafka
Structured Streaming with KafkaStructured Streaming with Kafka
Structured Streaming with Kafka
 
Introduction to Spark 2.0 Dataset API
Introduction to Spark 2.0 Dataset APIIntroduction to Spark 2.0 Dataset API
Introduction to Spark 2.0 Dataset API
 
Core Services behind Spark Job Execution
Core Services behind Spark Job ExecutionCore Services behind Spark Job Execution
Core Services behind Spark Job Execution
 
Introduction to Flink Streaming
Introduction to Flink StreamingIntroduction to Flink Streaming
Introduction to Flink Streaming
 
Multi Source Data Analysis using Spark and Tellius
Multi Source Data Analysis using Spark and TelliusMulti Source Data Analysis using Spark and Tellius
Multi Source Data Analysis using Spark and Tellius
 
Understanding time in structured streaming
Understanding time in structured streamingUnderstanding time in structured streaming
Understanding time in structured streaming
 
Building real time Data Pipeline using Spark Streaming
Building real time Data Pipeline using Spark StreamingBuilding real time Data Pipeline using Spark Streaming
Building real time Data Pipeline using Spark Streaming
 
Introduction to dataset
Introduction to datasetIntroduction to dataset
Introduction to dataset
 
Building scalable rest service using Akka HTTP
Building scalable rest service using Akka HTTPBuilding scalable rest service using Akka HTTP
Building scalable rest service using Akka HTTP
 
Anatomy of Data Source API : A deep dive into Spark Data source API
Anatomy of Data Source API : A deep dive into Spark Data source APIAnatomy of Data Source API : A deep dive into Spark Data source API
Anatomy of Data Source API : A deep dive into Spark Data source API
 
Introduction to Structured Streaming
Introduction to Structured StreamingIntroduction to Structured Streaming
Introduction to Structured Streaming
 
Spark architecture
Spark architectureSpark architecture
Spark architecture
 

Viewers also liked

Functional programming in Scala
Functional programming in ScalaFunctional programming in Scala
Functional programming in Scala
datamantra
 
Introduction to concurrent programming with Akka actors
Introduction to concurrent programming with Akka actorsIntroduction to concurrent programming with Akka actors
Introduction to concurrent programming with Akka actors
Shashank L
 
Levelling up in Akka
Levelling up in AkkaLevelling up in Akka
Levelling up in Akka
Sigmoid
 
An Updated Performance Comparison of Virtual Machines and Linux Containers
An Updated Performance Comparison of Virtual Machines and Linux ContainersAn Updated Performance Comparison of Virtual Machines and Linux Containers
An Updated Performance Comparison of Virtual Machines and Linux Containers
Kento Aoyama
 
Sensu Monitoring
Sensu MonitoringSensu Monitoring
Sensu Monitoring
Mohanasundaram Ponnusamy
 
Demystifying datastores
Demystifying datastoresDemystifying datastores
Demystifying datastores
vishnu rao
 
Redis overview
Redis overviewRedis overview
Redis overview
Ahmad El-khuja
 
Golang 101 (Concurrency vs Parallelism)
Golang 101 (Concurrency vs Parallelism)Golang 101 (Concurrency vs Parallelism)
Golang 101 (Concurrency vs Parallelism)
Pramesti Hatta K.
 
Security Monitoring with eBPF
Security Monitoring with eBPFSecurity Monitoring with eBPF
Security Monitoring with eBPF
Alex Maestretti
 
Introduction to Akka
Introduction to AkkaIntroduction to Akka
Introduction to Akka
Johan Andrén
 
Introduction of Mesosphere DCOS
Introduction of Mesosphere DCOSIntroduction of Mesosphere DCOS
Introduction of Mesosphere DCOS
Deughyeon Chang
 
Сергей Радзыняк ".NET Microservices in Real Life"
Сергей Радзыняк ".NET Microservices in Real Life"Сергей Радзыняк ".NET Microservices in Real Life"
Сергей Радзыняк ".NET Microservices in Real Life"
Fwdays
 
CloudConf2017 - Deploy, Scale & Coordinate a microservice oriented application
CloudConf2017 - Deploy, Scale & Coordinate a microservice oriented applicationCloudConf2017 - Deploy, Scale & Coordinate a microservice oriented application
CloudConf2017 - Deploy, Scale & Coordinate a microservice oriented application
Corley S.r.l.
 
Introduction To Anypoint CloudHub With Mulesoft
Introduction To Anypoint CloudHub With MulesoftIntroduction To Anypoint CloudHub With Mulesoft
Introduction To Anypoint CloudHub With Mulesoft
Jitendra Bafna
 
Redis原生命令介绍
Redis原生命令介绍Redis原生命令介绍
Redis原生命令介绍
简放 视野
 
Running .NET on Docker
Running .NET on DockerRunning .NET on Docker
Running .NET on Docker
Ben Hall
 
Magnetic door lock using arduino
Magnetic door lock using arduinoMagnetic door lock using arduino
Magnetic door lock using arduinoSravanthi Sinha
 
Data Pipelines in Hadoop - SAP Meetup in Tel Aviv
Data Pipelines in Hadoop - SAP Meetup in Tel Aviv Data Pipelines in Hadoop - SAP Meetup in Tel Aviv
Data Pipelines in Hadoop - SAP Meetup in Tel Aviv
larsgeorge
 
LCache DrupalCon Dublin 2016
LCache DrupalCon Dublin 2016LCache DrupalCon Dublin 2016
LCache DrupalCon Dublin 2016
David Timothy Strauss
 
Apache spark with Machine learning
Apache spark with Machine learningApache spark with Machine learning
Apache spark with Machine learning
datamantra
 

Viewers also liked (20)

Functional programming in Scala
Functional programming in ScalaFunctional programming in Scala
Functional programming in Scala
 
Introduction to concurrent programming with Akka actors
Introduction to concurrent programming with Akka actorsIntroduction to concurrent programming with Akka actors
Introduction to concurrent programming with Akka actors
 
Levelling up in Akka
Levelling up in AkkaLevelling up in Akka
Levelling up in Akka
 
An Updated Performance Comparison of Virtual Machines and Linux Containers
An Updated Performance Comparison of Virtual Machines and Linux ContainersAn Updated Performance Comparison of Virtual Machines and Linux Containers
An Updated Performance Comparison of Virtual Machines and Linux Containers
 
Sensu Monitoring
Sensu MonitoringSensu Monitoring
Sensu Monitoring
 
Demystifying datastores
Demystifying datastoresDemystifying datastores
Demystifying datastores
 
Redis overview
Redis overviewRedis overview
Redis overview
 
Golang 101 (Concurrency vs Parallelism)
Golang 101 (Concurrency vs Parallelism)Golang 101 (Concurrency vs Parallelism)
Golang 101 (Concurrency vs Parallelism)
 
Security Monitoring with eBPF
Security Monitoring with eBPFSecurity Monitoring with eBPF
Security Monitoring with eBPF
 
Introduction to Akka
Introduction to AkkaIntroduction to Akka
Introduction to Akka
 
Introduction of Mesosphere DCOS
Introduction of Mesosphere DCOSIntroduction of Mesosphere DCOS
Introduction of Mesosphere DCOS
 
Сергей Радзыняк ".NET Microservices in Real Life"
Сергей Радзыняк ".NET Microservices in Real Life"Сергей Радзыняк ".NET Microservices in Real Life"
Сергей Радзыняк ".NET Microservices in Real Life"
 
CloudConf2017 - Deploy, Scale & Coordinate a microservice oriented application
CloudConf2017 - Deploy, Scale & Coordinate a microservice oriented applicationCloudConf2017 - Deploy, Scale & Coordinate a microservice oriented application
CloudConf2017 - Deploy, Scale & Coordinate a microservice oriented application
 
Introduction To Anypoint CloudHub With Mulesoft
Introduction To Anypoint CloudHub With MulesoftIntroduction To Anypoint CloudHub With Mulesoft
Introduction To Anypoint CloudHub With Mulesoft
 
Redis原生命令介绍
Redis原生命令介绍Redis原生命令介绍
Redis原生命令介绍
 
Running .NET on Docker
Running .NET on DockerRunning .NET on Docker
Running .NET on Docker
 
Magnetic door lock using arduino
Magnetic door lock using arduinoMagnetic door lock using arduino
Magnetic door lock using arduino
 
Data Pipelines in Hadoop - SAP Meetup in Tel Aviv
Data Pipelines in Hadoop - SAP Meetup in Tel Aviv Data Pipelines in Hadoop - SAP Meetup in Tel Aviv
Data Pipelines in Hadoop - SAP Meetup in Tel Aviv
 
LCache DrupalCon Dublin 2016
LCache DrupalCon Dublin 2016LCache DrupalCon Dublin 2016
LCache DrupalCon Dublin 2016
 
Apache spark with Machine learning
Apache spark with Machine learningApache spark with Machine learning
Apache spark with Machine learning
 

Similar to Introduction to concurrent programming with akka actors

Java Threads: Lightweight Processes
Java Threads: Lightweight ProcessesJava Threads: Lightweight Processes
Java Threads: Lightweight Processes
Isuru Perera
 
Programming with Threads in Java
Programming with Threads in JavaProgramming with Threads in Java
Programming with Threads in Javakoji lin
 
Actors in the Small
Actors in the SmallActors in the Small
Actors in the Small
Bill La Forge
 
Actor Model Akka Framework
Actor Model Akka FrameworkActor Model Akka Framework
Actor Model Akka Framework
Harinath Krishnamoorthy
 
Reactive Software Systems
Reactive Software SystemsReactive Software Systems
Reactive Software Systems
Behrad Zari
 
Building stateful systems with akka cluster sharding
Building stateful systems with akka cluster shardingBuilding stateful systems with akka cluster sharding
Building stateful systems with akka cluster sharding
Knoldus Inc.
 
Multithreading programming in java
Multithreading programming in javaMultithreading programming in java
Multithreading programming in java
Elizabeth alexander
 
Dive into Akka Actors
Dive into Akka ActorsDive into Akka Actors
Dive into Akka Actors
Knoldus Inc.
 
Apache Airflow | What Is An Operator
Apache Airflow | What Is An OperatorApache Airflow | What Is An Operator
Apache Airflow | What Is An Operator
Marc Lamberti
 
Rethinking the debugger
Rethinking the debuggerRethinking the debugger
Rethinking the debugger
Iulian Dragos
 
Introdução à Elixir
Introdução à ElixirIntrodução à Elixir
Introdução à Elixir
Guilherme Oliveira
 
Akka-intro-training-public.pdf
Akka-intro-training-public.pdfAkka-intro-training-public.pdf
Akka-intro-training-public.pdf
BernardDeffarges
 
Concurrent/ parallel programming
Concurrent/ parallel programmingConcurrent/ parallel programming
Concurrent/ parallel programming
Tausun Akhtary
 
Unit 1 Core Java for Compter Science 3rd
Unit 1 Core Java for Compter Science 3rdUnit 1 Core Java for Compter Science 3rd
Unit 1 Core Java for Compter Science 3rd
prat0ham
 
Linux Internals - Part III
Linux Internals - Part IIILinux Internals - Part III
Linux Internals - Part III
Emertxe Information Technologies Pvt Ltd
 
Multithreading in Scala
Multithreading in Scala Multithreading in Scala
Multithreading in Scala
Knoldus Inc.
 
Reactive mistakes - ScalaDays Chicago 2017
Reactive mistakes -  ScalaDays Chicago 2017Reactive mistakes -  ScalaDays Chicago 2017
Reactive mistakes - ScalaDays Chicago 2017
Petr Zapletal
 
Multi threading
Multi threadingMulti threading
Multi threading
gndu
 
Concurrency Programming in Java - 01 - Introduction to Concurrency Programming
Concurrency Programming in Java - 01 - Introduction to Concurrency ProgrammingConcurrency Programming in Java - 01 - Introduction to Concurrency Programming
Concurrency Programming in Java - 01 - Introduction to Concurrency Programming
Sachintha Gunasena
 
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
sandhyakiran10
 

Similar to Introduction to concurrent programming with akka actors (20)

Java Threads: Lightweight Processes
Java Threads: Lightweight ProcessesJava Threads: Lightweight Processes
Java Threads: Lightweight Processes
 
Programming with Threads in Java
Programming with Threads in JavaProgramming with Threads in Java
Programming with Threads in Java
 
Actors in the Small
Actors in the SmallActors in the Small
Actors in the Small
 
Actor Model Akka Framework
Actor Model Akka FrameworkActor Model Akka Framework
Actor Model Akka Framework
 
Reactive Software Systems
Reactive Software SystemsReactive Software Systems
Reactive Software Systems
 
Building stateful systems with akka cluster sharding
Building stateful systems with akka cluster shardingBuilding stateful systems with akka cluster sharding
Building stateful systems with akka cluster sharding
 
Multithreading programming in java
Multithreading programming in javaMultithreading programming in java
Multithreading programming in java
 
Dive into Akka Actors
Dive into Akka ActorsDive into Akka Actors
Dive into Akka Actors
 
Apache Airflow | What Is An Operator
Apache Airflow | What Is An OperatorApache Airflow | What Is An Operator
Apache Airflow | What Is An Operator
 
Rethinking the debugger
Rethinking the debuggerRethinking the debugger
Rethinking the debugger
 
Introdução à Elixir
Introdução à ElixirIntrodução à Elixir
Introdução à Elixir
 
Akka-intro-training-public.pdf
Akka-intro-training-public.pdfAkka-intro-training-public.pdf
Akka-intro-training-public.pdf
 
Concurrent/ parallel programming
Concurrent/ parallel programmingConcurrent/ parallel programming
Concurrent/ parallel programming
 
Unit 1 Core Java for Compter Science 3rd
Unit 1 Core Java for Compter Science 3rdUnit 1 Core Java for Compter Science 3rd
Unit 1 Core Java for Compter Science 3rd
 
Linux Internals - Part III
Linux Internals - Part IIILinux Internals - Part III
Linux Internals - Part III
 
Multithreading in Scala
Multithreading in Scala Multithreading in Scala
Multithreading in Scala
 
Reactive mistakes - ScalaDays Chicago 2017
Reactive mistakes -  ScalaDays Chicago 2017Reactive mistakes -  ScalaDays Chicago 2017
Reactive mistakes - ScalaDays Chicago 2017
 
Multi threading
Multi threadingMulti threading
Multi threading
 
Concurrency Programming in Java - 01 - Introduction to Concurrency Programming
Concurrency Programming in Java - 01 - Introduction to Concurrency ProgrammingConcurrency Programming in Java - 01 - Introduction to Concurrency Programming
Concurrency Programming in Java - 01 - Introduction to Concurrency Programming
 
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
 

More from datamantra

State management in Structured Streaming
State management in Structured StreamingState management in Structured Streaming
State management in Structured Streaming
datamantra
 
Spark on Kubernetes
Spark on KubernetesSpark on Kubernetes
Spark on Kubernetes
datamantra
 
Understanding transactional writes in datasource v2
Understanding transactional writes in  datasource v2Understanding transactional writes in  datasource v2
Understanding transactional writes in datasource v2
datamantra
 
Optimizing S3 Write-heavy Spark workloads
Optimizing S3 Write-heavy Spark workloadsOptimizing S3 Write-heavy Spark workloads
Optimizing S3 Write-heavy Spark workloads
datamantra
 
Spark stack for Model life-cycle management
Spark stack for Model life-cycle managementSpark stack for Model life-cycle management
Spark stack for Model life-cycle management
datamantra
 
Testing Spark and Scala
Testing Spark and ScalaTesting Spark and Scala
Testing Spark and Scala
datamantra
 
Scalable Spark deployment using Kubernetes
Scalable Spark deployment using KubernetesScalable Spark deployment using Kubernetes
Scalable Spark deployment using Kubernetes
datamantra
 
Telco analytics at scale
Telco analytics at scaleTelco analytics at scale
Telco analytics at scale
datamantra
 
Platform for Data Scientists
Platform for Data ScientistsPlatform for Data Scientists
Platform for Data Scientists
datamantra
 
Real time ETL processing using Spark streaming
Real time ETL processing using Spark streamingReal time ETL processing using Spark streaming
Real time ETL processing using Spark streaming
datamantra
 
Anatomy of Spark SQL Catalyst - Part 2
Anatomy of Spark SQL Catalyst - Part 2Anatomy of Spark SQL Catalyst - Part 2
Anatomy of Spark SQL Catalyst - Part 2
datamantra
 
Anatomy of spark catalyst
Anatomy of spark catalystAnatomy of spark catalyst
Anatomy of spark catalyst
datamantra
 

More from datamantra (12)

State management in Structured Streaming
State management in Structured StreamingState management in Structured Streaming
State management in Structured Streaming
 
Spark on Kubernetes
Spark on KubernetesSpark on Kubernetes
Spark on Kubernetes
 
Understanding transactional writes in datasource v2
Understanding transactional writes in  datasource v2Understanding transactional writes in  datasource v2
Understanding transactional writes in datasource v2
 
Optimizing S3 Write-heavy Spark workloads
Optimizing S3 Write-heavy Spark workloadsOptimizing S3 Write-heavy Spark workloads
Optimizing S3 Write-heavy Spark workloads
 
Spark stack for Model life-cycle management
Spark stack for Model life-cycle managementSpark stack for Model life-cycle management
Spark stack for Model life-cycle management
 
Testing Spark and Scala
Testing Spark and ScalaTesting Spark and Scala
Testing Spark and Scala
 
Scalable Spark deployment using Kubernetes
Scalable Spark deployment using KubernetesScalable Spark deployment using Kubernetes
Scalable Spark deployment using Kubernetes
 
Telco analytics at scale
Telco analytics at scaleTelco analytics at scale
Telco analytics at scale
 
Platform for Data Scientists
Platform for Data ScientistsPlatform for Data Scientists
Platform for Data Scientists
 
Real time ETL processing using Spark streaming
Real time ETL processing using Spark streamingReal time ETL processing using Spark streaming
Real time ETL processing using Spark streaming
 
Anatomy of Spark SQL Catalyst - Part 2
Anatomy of Spark SQL Catalyst - Part 2Anatomy of Spark SQL Catalyst - Part 2
Anatomy of Spark SQL Catalyst - Part 2
 
Anatomy of spark catalyst
Anatomy of spark catalystAnatomy of spark catalyst
Anatomy of spark catalyst
 

Recently uploaded

Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
ThomasParaiso2
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
James Anderson
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
Neo4j
 

Recently uploaded (20)

Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
 

Introduction to concurrent programming with akka actors

  • 1. Introduction to Concurrent programming with Akka Actors https://github.com/shashankgowdal/introduction-to-concurrentprogrammin g-with-akka
  • 2. ● Shashank L ● Senior Software engineer at Tellius ● Part time big data consultant and trainer at datamantra.io ● www.shashankgowda.com
  • 3. Concurrency ● Concurrency is the decomposability property of a program, algorithm, or problem into order-independent or partially-ordered components or units ● Structure a program by breaking it into pieces that can be executed independently ● Co ordinating the execution of independent pieces
  • 4. Concurrency and parallelism ● Concurrency is dealing with more than one thing at once ● Parallelism is doing more than one thing at once Given tasks T1 and T2 T1 may be executed and finished before T2 or vice versa (serial and sequential) T1 and T2 may be executed alternately (serial and concurrent) T1 and T2 may be executed simultaneously at the same instant of time (parallel and concurrent)
  • 5. Concurrency is not parallelism ● Queues can be thought of processed/threads ● Vending machine is processor core
  • 6. Moore’s law The number of transistors on a chip doubles approximately every 2 years. ~ Gordon Moore, 1965
  • 7. Free performance lunch ● Over 30 years till 2000, performance gains were in 3 areas ○ Clock speed ○ Execution optimization ○ Caching Old applications have always run significantly faster even without being recompiled
  • 8. Moore’s law ● Early 2000 ○ Chips got big, transistors were added aggressively ○ Clock cycle was almost unchanged ○ Heat dissipation issues ○ Power consumption ○ Current leakage
  • 10. Birth of Multicore processors ● Multi-core processors ● Handle multiple operations in parallel ● CPU speeds are not increasing drastically anytime soon ● No free performance lunch without significant redesign ● Performance gains in new chips will be fueled by three main approaches ○ Hyperthreading ○ Multicore ○ cache
  • 11. Free performance lunch is over ● Concurrency revolution ● Build multi core aware applications ● Operate in concurrent fashion ● Scale horizontally
  • 12. Types of Concurrency ● Shared state concurrency ● Software transactional concurrency ● Message passing concurrency
  • 13. Shared state concurrency ● Shared mutability ● Memory blocks can be access simultaneously by multiple programs ● Race condition ● Dead locks ● Blocking calls com.shashank.akka.basic.ThreadUnsafeBuffer
  • 14. Software transactional memory ● Shared, managed mutability ● Objects can be mutated only within a transaction ● STM keeps track of changes made in a particular ● Once transaction is completed, it validates and commits the results ● Validation fails when others have committed the result ● Transaction will be repeated with the updated value.
  • 15. Message passing concurrency ● Isolated mutability ● Mutable objects are isolated from the threads ● Threads will not be able to directly access the objects ● Access to the mutable objects is done through messages ● Sending message can be asynchronous and nonblocking
  • 16. Joe Armstrong’s words The world is concurrent. It is parallel. Pure message-passing concurrency is what we do all the time. Imagine a group of people. They have no shared state. I have my private memory (in my head) and you have yours. It is NOT shared. We communicate by passing messages (sound and light waves). We update our private state based on the reception of these messages. That’s Concurrency Oriented Programming in a nutshell.
  • 17. Actors ● From a 1973 paper, written by Carl Hewitt ● First major adoption was done by Ericsson in 80s ○ Invented Erlang and open sourced in 90s ○ Built a distributed, concurrent, and fault-tolerant telcom system which has 99.9999999% uptime ● Implements Message-Passing or Isolated mutability based concurrency
  • 18. Actor model ● Share Nothing ○ No need to synchronize. ● Isolated. Lightweight event-based Processes ○ ~ 6.5m on 4GB RAM ● Communicate through Messages ○ Asynchronous and Nonblocking ○ Messages are immutable ● Each actor has a mailbox (message queue) ● Scalable and fast
  • 19. When an Actor receives messages ● Creates new actors ● Send message to other actors/self ● Designate how it should handle the next message
  • 20. Akka ● Founded by Jonas Boner and now part of Typesafe stack ● Actor implementation on JVM - Scala ○ Java API and Scala API ● Provides a framework to create & manage actors ● Backed by JVM Thread model ● Akka provides a mailbox for each actor ○ in-memory queue to stage messages ● Clients can send messages synchronously or asynchronously ● Actor receives messages and respond to clients
  • 21.
  • 22. Actor System ● Actors are created within this context ● Fundamental unit that embodies: Processing, storage and communication ● Manage shared facilities: scheduling, logging, configuration etc ● Can have many per JVM with different configs ● Can contain millions of actors
  • 24. DEFINE class LoggerActor extends Actor { def receive = { case x:String => println(x) case _ => println("huh?") } }
  • 25. CREATE val system = ActorSystem("LogSystem") val loggerActor = system.actorOf( Props[LoggerActor], name = "loggeractor")
  • 26. SEND ● Fire and forget ○ Async ○ No expected reply ○ ! or tell() ● Send and Receive ○ Async ○ Expects reply (Future) ○ ? or ask()
  • 27. SEND - Fire and forget //No need to return anything in the receive method def receive = { case x:Int => println(x) } //Send the message and don’t wait for the reply actorRef ! (100) com.shashank.akka.basic.SimpleActor
  • 28. SEND - Send and receive //Use the sender method to get the actorRef of the sender def receive = { case "hello" => sender() ! ("hello how are you?") } //Send the message and get a future back, we can wait for that future to be successful to get the result val responseFuture = bufferActor ? ("hello") responseFuture onSuccess{ case response => println(response) } com.shashank.akka.basic.ThreadSafeBuffer
  • 30. Mailbox ActorRef Mailbox Actor Instance Invokes Actor Instance with Message Runs on dispatcher - abstracts threading
  • 32. BECOME ● Dynamically redefines actor behaviour ● Reactively triggered by message ● Like changing an interface or implementation on-the-fly com.shashank.akka.basic.ThreadSafeBufferWithLimit
  • 33. How error handling is done in Java ● 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 ● Errors do not propagate between threads ● This leads to Defensive programming with ○ Error handling tangled with business logic ○ Error handling scattered all over the code
  • 34. SUPERVISE ● Manage another actor’s failure ● Supervisor receives notification and it can react upon failure ● Every actor has a default supervisor strategy ○ Can be overridden
  • 35. SUPERVISE ● On Failure, Supervisor decides what happens next ○ Resume child and keep the internal state ○ Restart child and wipe the internal state ○ Stop child permanently ○ Stop itself and escalate the error ● OneForOneStrategy affects only failed child ● AllForOneStrategy affects all the children com.shashank.akka.supervision.BasicSupervision
  • 38. Actor can form a hierarchy
  • 39. Actor can form a hierarchy
  • 40. Name resolution - like a file system
  • 41. Stopping Actors //Shutting down the Actor System system.shutdown() //Sending PoisonPill message actorRef ? (PoisonPill) //Shutting the actor from inside the actor context.stop(self) //Shutting another actor from inside the actor context.stop(actorRef) com.shashank.akka.basic.ShuttingDown
  • 42. Message delivery ● At most once - No guaranteed delivery ● Cheapest ● Highest performance ● Least implementation overhead ● It can be done in a fire-and-forget fashion without keeping state at the sending end or in the transport mechanism ● At least once - Akka persistence
  • 43. Message ordering ● Message ordering per sender-receiver pair
  • 44. Dispatcher ● Controls and coordinates the message dispatching to the actors ● Make sure that the resources are optimized and messages are processed as fast as possible ● Dispatch policies that can be customized(number of cores or memory available)
  • 45. Dispatcher ● Runways - Threads ● Airlines - Mailboxes ● ATC - Dispatcher or Dispatch policy
  • 47. Dispatcher and Mailboxes Types of dispatchers ● Dispatcher ● Pinned dispatcher ● Balancing dispatcher ● Calling thread dispatcher Mailbox implementations ● Unbounded mailbox ● Bounded mailbox ● Unbounded priority mailbox ● Bounded priority mailbox
  • 48. ● Entity that directs the message from source to the destination actor ● Router is also a type of actor ● Does not make use of the store-and-forward mechanism ● Routers dispatch the incoming messages directly to the destination actor’s mailboxes system.actorOf(Props[MyActor].withRouter(RoundRobinRouter(nrOfInstances = 5))) Routers
  • 49. ● Round robin router It routes the incoming messages in a circular order to all its routees ● Random router It randomly selects a routee and routes the message to the same ● Smallest mailbox router It identifies the actor with the least number of messages in its mailbox and routes the message to the same ● Broadcast router It forwards the same message to all the routees ● Scatter gather first completed router It forwards the message to all its routees as a future, then whichever routee actor responds back, it takes the results and sends them back to the caller com.shashank.akka.basic.Router Types of Routers
  • 50. def preStart(): Unit = () def postStop(): Unit = () def preRestart(reason: Throwable, message: Option[Any]): Unit = { context.children foreach { child ⇒ context.stop(child) } postStop() } def postRestart(reason: Throwable): Unit = { preStart() } Actor API
  • 51. ● A path is a place that can be occupied by a living actor ● When actorOf() is called it assigns an incarnation of the actor described by the passed Props to the given path ● An ActorRef always represents an incarnation (path and UID) not just a given path. Another actor created later with the same name will have a different ActorRef // will look up this absolute path context.actorSelection("/user/serviceA/aggregator") // will look up sibling beneath same supervisor context.actorSelection("../joe") Actor Path
  • 53. ● Consists of 2 parts ○ A public interface ○ An implementation ● Similar to Interface and implements in Java, Traits in Scala ● TypedActors have a static contract ● Some features like become is not available ● Bridging between actor systems (the “inside”) and non-actor code (the “outside”) Typed actors
  • 54. def squareDontCare(i: Int): Unit //fire-forget def square(i: Int): Future[Int] //non-blocking send-request-reply def squareNowPlease(i: Int): Option[Int] //blocking send-request-reply def squareNow(i: Int): Int //blocking send-request-reply @throws(classOf[Exception]) //declare it or you will get an UndeclaredThrowableException def squareTry(i: Int): Int //blocking send-request-reply with possible exception //Creating an actorRef of a TypedActor val mySquarer: Squarer = TypedActor(system).typedActorOf(TypedProps[SquarerImpl]()) com.shashank.akka.basic.TypedActorExample Typed actors
  • 55. ● Dedicated module akka-testkit for supporting tests ● Testing isolated pieces of code without involving the actor model, meaning without multiple threads ● Testing (multiple) encapsulated actors including multi-threaded scheduling ● Integration with ScalaTest to write more readable assertions com.shashank.akka.supervision.SupervisorTestSpec Actor TestKit
  • 56. ● All configuration for Akka is held within instances of ActorSystem ● ActorSystem is the only consumer of configuration information ● Parse the configuration file val config = ConfigFactory.parseFile(new File("src/main/resources/router/application.conf")) val system = ActorSystem("NameOfActorSystem", config) ● Read the configuration files automatically from ClassLoader val config = ConfigFactory.defaultReference() val system = ActorSystem("NameOfActorSystem", config) ● Parse all application.conf, application.json and application.properties ● akka.log-config-on-start Configuration - TypeSafe config
  • 57. ● Distributed by default ● Messages should be and are serializable ● ActorRefs are serializable ● Probability of the message reaching is higher than local JVM ● No separate remoting layer in Akka. Purely driven by config ● Communication between involved system is symmetric ● Not possible to create pure client-server setups Remote Actors
  • 59. In different scenarios Actors can be alternatives for: ● A thread ● An object instance or component ● A callback or listener ● A singleton or service ● A router, load-balancer or pool ● An out-of-service process ● A Finite State machine (FSM) What can I use Actors for?
  • 60. ● http://doc.akka.io/docs/akka/2.4/scala ● http://blog.madhukaraphatak.com/simple-akka-remote-example/ ● https://www.youtube.com/watch?v=W_l57iyn4mU Programming with Actors by Venkat ● https://www.slideshare.net/jboner/introducing-akka ● https://www.slideshare.net/RoyRusso1/introduction-to-akka-atlanta-ja va-users-group ● https://blog.golang.org/concurrency-is-not-parallelism References