SlideShare a Scribd company logo
MADRID · NOV 27-28 · 2015
Scala Programming @ Madrid
Akka voló sobre el nido del Future
Javier Santos
David Vallejo
MADRID · NOV 27-28 · 2015
Scala Programming @ Madrid
About us
David Vallejo @dvnavarro
« It’s not a bug – it’s an
undocumented feature.»
Anonymous
Javier Santos @jpaniego
«Hay dos formas de programar sin
errores; solo la tercera funciona»
Alan J Perlis
MADRID · NOV 27-28 · 2015
Scala Programming @ Madrid
Introduction: A functional world
● Purely functional: whole world could be implemented
in a single functional line
● Functional features
○ Robust
○ Debuggable
○ Predictable
○ Pluggable
MADRID · NOV 27-28 · 2015
Scala Programming @ Madrid
Introduction: A functional world
● Example
type Context = (Input,Output,Error)
type Action = Context => (Context,Event)
def main(
actions: Iterable[Action],
context: Context):(Context,Seq[Event]) = {
((context,Seq.empty[Event]) /: actions) {
case ((context,events),action) =>
action.apply(context) match {
case (context,event) => (context, events :+ event)
}
}
}
MADRID · NOV 27-28 · 2015
Scala Programming @ Madrid
MADRID · NOV 27-28 · 2015
Scala Programming @ Madrid
Introduction: A functional world
● Problem? World actions are not precalculated.
What happens to I/O?
● World can be considered as
○ asynchronous: Things may happen at same time
○ reactive: Things may happen due to
■ actions: that trigger …
■ ...events: action consequences.
MADRID · NOV 27-28 · 2015
Scala Programming @ Madrid
Introduction: Runnable & Callable
● java.lang.Runnable
trait Runnable {
def run(): Unit
}
● java.util.concurrent.Callable
trait Callable[V] {
def call(): V
}
MADRID · NOV 27-28 · 2015
Scala Programming @ Madrid
Introduction: Threads
● Scala’s concurrency model is built on Java’s
● java.lang.Thread
val myThread = new Thread(new Runnable {
def run(){
println(“hi”)
}
}
myThread.start()
● Thread improvements (ExecutorService ~ Thread pool)
● Anyway, Threads abstraction level is too low
MADRID · NOV 27-28 · 2015
Scala Programming @ Madrid
What about Scala and threads?
MADRID · NOV 27-28 · 2015
Scala Programming @ Madrid
Future: Overview
● By default, non-blocking operations
● They will hold a T value at some point
● So a future may be uncompleted(it has no value yet) or
completed
● Completion will be treated as a scala.util.Try value
It will have two possible values:
○ Success(t: T)
○ Failure(t: Throwable)
MADRID · NOV 27-28 · 2015
Scala Programming @ Madrid
Future: Overview
● Future example
import scala.concurrent._
import ExecutionContext.Implicits.global
val firstPrimeNumbers: Future[List[Int]] = Future {
List(1,2,3,5,7,11,13)
//what if 'calculateFirstPrimeNumbers(100000000)'…
}
res0: Future[List[Int]]
MADRID · NOV 27-28 · 2015
Scala Programming @ Madrid
Future: Overview
● Failing Future example
import scala.concurrent._
import ExecutionContext.Implicits.global
val thisWillFail: Future[Int] = Future(2 / 0)
res0: Future[Int]
MADRID · NOV 27-28 · 2015
Scala Programming @ Madrid
Future: ExecutionContext
● A future, once it’s completed, it never changes of value
● An ExecutionContext
○ executes tasks submitted to them.
○ They can be seen as thread pools.
○ Most of future ops require an implicit
ExecutionContext.
MADRID · NOV 27-28 · 2015
Scala Programming @ Madrid
Future: Expecting results
● Expecting results.
○ Blocker way (discouraged but sometimes
mandatory).
○ Non-blocker way: using callbacks
MADRID · NOV 27-28 · 2015
Scala Programming @ Madrid
Future: Blocking - Await
● Blocking: Await.result / Await.ready
import scala.concurrent._
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global
val f: Future[Int] = Future{
Thread.sleep(10000)
2
}
println(Await.result(f,12.seconds))
//2
MADRID · NOV 27-28 · 2015
Scala Programming @ Madrid
Future: Blocking - Await
● Blocking: Await (Problem: Not enough time)
import scala.concurrent._
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global
val f: Future[Int] = Future{
Thread.sleep(10000)
2
}
println(Await.result(f,5.seconds))
java.util.concurrent.TimeoutException: Futures timed out after
[5 seconds]
MADRID · NOV 27-28 · 2015
Scala Programming @ Madrid
Future: Non-blocking - Callbacks
● Non-Blocking: callbacks
import scala.concurrent._
import scala.concurrent.ExecutionContext.Implicits.global
val f: Future[Int] = Future{
Thread.sleep(10000)
2
}
f.onComplete( n => println(n) )
//at some point, “Success(2)” will appear
Non-blocking
MADRID · NOV 27-28 · 2015
Scala Programming @ Madrid
Future: Callbacks
● Callbacks will be executed asynchronously when future
is completed
● type Callback = Try[T] => Unit
● Try[T] ~ Either[Throwable,T]
○ Left(throwable) ~ Failure(throwable)
○ Right(t) ~ Success(t)
MADRID · NOV 27-28 · 2015
Scala Programming @ Madrid
Future: Callbacks
● onComplete
f.onComplete( (t: Try[Int]) => println(t) )
//Success(2)
● onSuccess
f.onSuccess( n => println(n) )
//2
● onFailure
f.onFailure( throwable => println(throwable.getMessage) )
//it will never print an error (because it equals Success(2))
MADRID · NOV 27-28 · 2015
Scala Programming @ Madrid
Future: Operations
● map
def getFirstMillionOfPrimes(): Future[List[Int]] = ???
getFirstMillionOfPrimes().map(
(list: List[Int]) => list.head)
res0: Future[Int]
MADRID · NOV 27-28 · 2015
Scala Programming @ Madrid
Future: Operations
● flatMap
def getFirstMillionOfPrimes(): Future[List[Int]] = ???
def concatenate(l: List[Int]): Future[String] = ???
getFirstMillionOfPrimes().flatMap(
(list: List[Int]) => concatenate(list))
res0: Future[String]
MADRID · NOV 27-28 · 2015
Scala Programming @ Madrid
Future: Monad behavior
● Composition
○ Future is like a monad
■ Point Function: Future.apply
■ Bind Function: flatMap
■ Some math properties and so...
○ Since Future has map,flatMap,filter methods;
it can be composed easily in a for-comprehension
MADRID · NOV 27-28 · 2015
Scala Programming @ Madrid
MADRID · NOV 27-28 · 2015
Scala Programming @ Madrid
Future: Composition
● Problem
var result: String = “”
val f1: Future[Unit] = Future{
result += “Hi ”
}
val f2: Future[Unit] = Future{
result += “ everyone”
}
● result value? “Hi everyone”? “ everyoneHi”?
MADRID · NOV 27-28 · 2015
Scala Programming @ Madrid
MADRID · NOV 27-28 · 2015
Scala Programming @ Madrid
Future: Composition
● for-comprehension is your friend
for {
primes <- getFirstMillionPrimes()
primesString <- concatenate(primes)
} yield primesString
res0: Future[String]
Future[List[Int]]
Future[String]
MADRID · NOV 27-28 · 2015
Scala Programming @ Madrid
Future: Recovering from failure
● recover
val f: Future[Int] = Future{
1 / 0
}.recover{
case e: ArithmeticException => 0
}
MADRID · NOV 27-28 · 2015
Scala Programming @ Madrid
Future: Recovering from failure
● recoverWith
val f: Future[Int] = Future{
1 / 0
}.recoverWith{
case e: ArithmeticException => Future(0)
}
MADRID · NOV 27-28 · 2015
Scala Programming @ Madrid
Future: Recovering from failure
● fallbackTo
val f1: Future[Int] = Future{
1 / 0
}
val f2: Future[Int] = Future(0)
val f = f1 fallbackTo f2
MADRID · NOV 27-28 · 2015
Scala Programming @ Madrid
Promise: Overview
● Futures can be created by
○ Future.apply
○ Promises
● You can think about it like
○ Future ~ Read future value
○ Promise ~ Write future value
● Promises are single-assigned (just once. Immutable as
futures)
MADRID · NOV 27-28 · 2015
Scala Programming @ Madrid
Promise: Baggage & claim
Menu
order
Menu
Being
Cooked
Ticket
Menu ready
MADRID · NOV 27-28 · 2015
Scala Programming @ Madrid
Promise: Baggage & claim
Begin
completion
Future[T]
p.success
or
p.failure
Try[T]
Promise[T]
MADRID · NOV 27-28 · 2015
Scala Programming @ Madrid
Promise: example
val r: T = produceSomething()
p success r
doSomethingElse()
startDoingSomething()
f onSuccess {
case r: T => handleResult()
}
val p = promise[T]
val f = p.future
Producer Consumer
MADRID · NOV 27-28 · 2015
Scala Programming @ Madrid
Promise: completion
● complete
val p = promise[Int]
p.complete(Try(2))
● completeWith
val p = promise[Int]
p.completeWith(Future(2))
MADRID · NOV 27-28 · 2015
Scala Programming @ Madrid
Future alternatives
● Scalaz futures
● Scala’s async library
MADRID · NOV 27-28 · 2015
Scala Programming @ Madrid
Tones of slides and however...
Futures/Promises
Akka actors
MADRID · NOV 27-28 · 2015
Scala Programming @ Madrid
MADRID · NOV 27-28 · 2015
Scala Programming @ Madrid
Akka: main concepts
● Actors, actors everywhere
● Asynchronous messages
● Event-driven processes
● Distributed systems
MADRID · NOV 27-28 · 2015
Scala Programming @ Madrid
Akka: Actors
● Black box
● State without race condition
● Messages to update the state
MADRID · NOV 27-28 · 2015
Scala Programming @ Madrid
Akka: Actors
class MyFirstActor extends Actor {
override def receive = {
case _ => println("Hello World!")
}
}
MADRID · NOV 27-28 · 2015
Scala Programming @ Madrid
Akka: Send a message
● Tell message
actor ! "Hi"
● Ask message
actor ? "Are you there"
MADRID · NOV 27-28 · 2015
Scala Programming @ Madrid
Akka: Ask pattern
implicit val timeout = Timeout(5 seconds)
val f: Future[String] =
(actorRef ? AreYouThere).mapTo[String]
MADRID · NOV 27-28 · 2015
Scala Programming @ Madrid
Akka: An example
MADRID · NOV 27-28 · 2015
Scala Programming @ Madrid
Akka: Services user
service
contact
service
address
service
System
GetUser(id)
GetContacts(name)
GetAddress(name)
Option[User]
List[Contact]
Address
UserInfo
MADRID · NOV 27-28 · 2015
Scala Programming @ Madrid
Akka: Ask Pattern & For
Comprehension
class UserServiceActor extends Actor {
val users: Map[String, User] =
Map("1" -> User("John"), "2" -> User("Jack"))
override def receive = {
case GetUser(userId: String) =>
sender ! users.get(userId)
}
}
MADRID · NOV 27-28 · 2015
Scala Programming @ Madrid
Akka: Ask Pattern & For
Comprehension
def getInfo(userId: String): Future[UserInfo] =
for {
Some(user) <- (usersActor ? GetUser(userId))
.mapTo[Option[User]]
contacts <- (contactsActor.?(GetContacts(user.name))
(Timeout(5 seconds),context.self))
.mapTo[List[Contact]]
address <- (addressesActor ? GetAddress(user.name))
.mapTo[Address]
} yield UserInfo(user, contacts, address)
MADRID · NOV 27-28 · 2015
Scala Programming @ Madrid
MADRID · NOV 27-28 · 2015
Scala Programming @ Madrid
scalera.es
@scalerablog
MADRID · NOV 27-28 · 2015
Scala Programming @ Madrid
MADRID · NOV 27-28 · 2015
Scala Programming @ Madrid
Primeros pasos con Akka:
Olvídate de los threads
27 NOVEMBER
TRACK D
18:00
MADRID · NOV 27-28 · 2015
Scala Programming @ Madrid
Caminando de Java a Scala en
menos de 2 horas
28 NOVEMBER
TRACK B
9:30
MADRID · NOV 27-28 · 2015
Scala Programming @ Madrid
MADRID · NOV 27-28 · 2015
Scala Programming @ Madrid
Akka voló sobre el nido del Future
Javier Santos
David Vallejo

More Related Content

What's hot

Aggregate Programming in Scala
Aggregate Programming in ScalaAggregate Programming in Scala
Aggregate Programming in Scala
Roberto Casadei
 
Spark: Taming Big Data
Spark: Taming Big DataSpark: Taming Big Data
Spark: Taming Big Data
Leonardo Gamas
 
Practical Aggregate Programming in Scala
Practical Aggregate Programming in ScalaPractical Aggregate Programming in Scala
Practical Aggregate Programming in Scala
Roberto Casadei
 
Value objects in JS - an ES7 work in progress
Value objects in JS - an ES7 work in progressValue objects in JS - an ES7 work in progress
Value objects in JS - an ES7 work in progress
Brendan Eich
 
Parallel sorting Algorithms
Parallel  sorting AlgorithmsParallel  sorting Algorithms
Parallel sorting Algorithms
GARIMA SHAKYA
 
Data Mining: Implementation of Data Mining Techniques using RapidMiner software
Data Mining: Implementation of Data Mining Techniques using RapidMiner softwareData Mining: Implementation of Data Mining Techniques using RapidMiner software
Data Mining: Implementation of Data Mining Techniques using RapidMiner software
Mohammed Kharma
 
Bitonic Sort in Shared SIMD Array Processor
Bitonic Sort in Shared SIMD Array ProcessorBitonic Sort in Shared SIMD Array Processor
Bitonic Sort in Shared SIMD Array Processor
Asanka Dilruk
 
Clojure
ClojureClojure
Clojure
Rohit Vaidya
 
(chapter 7) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 7) A Concise and Practical Introduction to Programming Algorithms in...(chapter 7) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 7) A Concise and Practical Introduction to Programming Algorithms in...
Frank Nielsen
 
Intro to JavaScript - Week 4: Object and Array
Intro to JavaScript - Week 4: Object and ArrayIntro to JavaScript - Week 4: Object and Array
Intro to JavaScript - Week 4: Object and Array
Jeongbae Oh
 
Digital Publishing for Scale: The Economist and Go
Digital Publishing for Scale: The Economist and GoDigital Publishing for Scale: The Economist and Go
Digital Publishing for Scale: The Economist and Go
C4Media
 

What's hot (11)

Aggregate Programming in Scala
Aggregate Programming in ScalaAggregate Programming in Scala
Aggregate Programming in Scala
 
Spark: Taming Big Data
Spark: Taming Big DataSpark: Taming Big Data
Spark: Taming Big Data
 
Practical Aggregate Programming in Scala
Practical Aggregate Programming in ScalaPractical Aggregate Programming in Scala
Practical Aggregate Programming in Scala
 
Value objects in JS - an ES7 work in progress
Value objects in JS - an ES7 work in progressValue objects in JS - an ES7 work in progress
Value objects in JS - an ES7 work in progress
 
Parallel sorting Algorithms
Parallel  sorting AlgorithmsParallel  sorting Algorithms
Parallel sorting Algorithms
 
Data Mining: Implementation of Data Mining Techniques using RapidMiner software
Data Mining: Implementation of Data Mining Techniques using RapidMiner softwareData Mining: Implementation of Data Mining Techniques using RapidMiner software
Data Mining: Implementation of Data Mining Techniques using RapidMiner software
 
Bitonic Sort in Shared SIMD Array Processor
Bitonic Sort in Shared SIMD Array ProcessorBitonic Sort in Shared SIMD Array Processor
Bitonic Sort in Shared SIMD Array Processor
 
Clojure
ClojureClojure
Clojure
 
(chapter 7) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 7) A Concise and Practical Introduction to Programming Algorithms in...(chapter 7) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 7) A Concise and Practical Introduction to Programming Algorithms in...
 
Intro to JavaScript - Week 4: Object and Array
Intro to JavaScript - Week 4: Object and ArrayIntro to JavaScript - Week 4: Object and Array
Intro to JavaScript - Week 4: Object and Array
 
Digital Publishing for Scale: The Economist and Go
Digital Publishing for Scale: The Economist and GoDigital Publishing for Scale: The Economist and Go
Digital Publishing for Scale: The Economist and Go
 

Viewers also liked

Blue sky credentials may 6th 2012 eng biilboard focus ver 2003 print
Blue sky credentials may 6th 2012 eng biilboard focus ver 2003 printBlue sky credentials may 6th 2012 eng biilboard focus ver 2003 print
Blue sky credentials may 6th 2012 eng biilboard focus ver 2003 printKelvin Tran
 
Scientific Revolution
Scientific RevolutionScientific Revolution
Scientific Revolution
Jian Chang
 
GENeral Admission: A Consumer Behavior Approach in Marketing to the Millennia...
GENeral Admission: A Consumer Behavior Approach in Marketing to the Millennia...GENeral Admission: A Consumer Behavior Approach in Marketing to the Millennia...
GENeral Admission: A Consumer Behavior Approach in Marketing to the Millennia...
Vino Mazzei
 
Digital credential
Digital credentialDigital credential
Digital credentialKelvin Tran
 

Viewers also liked (7)

common things Team 11788
common things Team 11788common things Team 11788
common things Team 11788
 
Blue sky credentials may 6th 2012 eng biilboard focus ver 2003 print
Blue sky credentials may 6th 2012 eng biilboard focus ver 2003 printBlue sky credentials may 6th 2012 eng biilboard focus ver 2003 print
Blue sky credentials may 6th 2012 eng biilboard focus ver 2003 print
 
Vald aosta 2
Vald aosta 2Vald aosta 2
Vald aosta 2
 
Scientific Revolution
Scientific RevolutionScientific Revolution
Scientific Revolution
 
Lezione1
Lezione1Lezione1
Lezione1
 
GENeral Admission: A Consumer Behavior Approach in Marketing to the Millennia...
GENeral Admission: A Consumer Behavior Approach in Marketing to the Millennia...GENeral Admission: A Consumer Behavior Approach in Marketing to the Millennia...
GENeral Admission: A Consumer Behavior Approach in Marketing to the Millennia...
 
Digital credential
Digital credentialDigital credential
Digital credential
 

Similar to Codemotion akka voló sobre el nido del future

RxJava in practice
RxJava in practice RxJava in practice
RxJava in practice
Javier Gamarra
 
Scala for dummies
Scala for dummiesScala for dummies
Scala for dummies
Javier Santos Paniego
 
Railroading into Scala
Railroading into ScalaRailroading into Scala
Railroading into Scala
Nehal Shah
 
Introduction to Asynchronous scala
Introduction to Asynchronous scalaIntroduction to Asynchronous scala
Introduction to Asynchronous scalaStratio
 
Scala.pdf
Scala.pdfScala.pdf
Scala.pdf
ssuser155dbc1
 
Standardizing JavaScript Decorators in TC39 (Full Stack Fest 2019)
Standardizing JavaScript Decorators in TC39 (Full Stack Fest 2019)Standardizing JavaScript Decorators in TC39 (Full Stack Fest 2019)
Standardizing JavaScript Decorators in TC39 (Full Stack Fest 2019)
Igalia
 
Object oriented programming with java pdf
Object oriented programming with java pdfObject oriented programming with java pdf
Object oriented programming with java pdf
sonivipin2342
 
Developing a new Scala DSL for Apache Camel
Developing a new Scala DSL for Apache CamelDeveloping a new Scala DSL for Apache Camel
Developing a new Scala DSL for Apache Camelelliando dias
 
Scilab: Computing Tool For Engineers
Scilab: Computing Tool For EngineersScilab: Computing Tool For Engineers
Scilab: Computing Tool For Engineers
Naren P.R.
 
Introduction to MATLAB
Introduction to MATLABIntroduction to MATLAB
Introduction to MATLAB
Bhavesh Shah
 
Two Days workshop on MATLAB
Two Days workshop on MATLABTwo Days workshop on MATLAB
Two Days workshop on MATLABBhavesh Shah
 
Debugging and Profiling C++ Template Metaprograms
Debugging and Profiling C++ Template MetaprogramsDebugging and Profiling C++ Template Metaprograms
Debugging and Profiling C++ Template Metaprograms
Platonov Sergey
 
Porting R Models into Scala Spark
Porting R Models into Scala SparkPorting R Models into Scala Spark
Porting R Models into Scala Spark
carl_pulley
 
Programming in Scala: Notes
Programming in Scala: NotesProgramming in Scala: Notes
Programming in Scala: Notes
Roberto Casadei
 

Similar to Codemotion akka voló sobre el nido del future (20)

RxJava in practice
RxJava in practice RxJava in practice
RxJava in practice
 
Scala for dummies
Scala for dummiesScala for dummies
Scala for dummies
 
Railroading into Scala
Railroading into ScalaRailroading into Scala
Railroading into Scala
 
Introduction to Asynchronous scala
Introduction to Asynchronous scalaIntroduction to Asynchronous scala
Introduction to Asynchronous scala
 
Scala.pdf
Scala.pdfScala.pdf
Scala.pdf
 
Standardizing JavaScript Decorators in TC39 (Full Stack Fest 2019)
Standardizing JavaScript Decorators in TC39 (Full Stack Fest 2019)Standardizing JavaScript Decorators in TC39 (Full Stack Fest 2019)
Standardizing JavaScript Decorators in TC39 (Full Stack Fest 2019)
 
Object oriented programming with java pdf
Object oriented programming with java pdfObject oriented programming with java pdf
Object oriented programming with java pdf
 
Camel Scala
Camel ScalaCamel Scala
Camel Scala
 
camel-scala.pdf
camel-scala.pdfcamel-scala.pdf
camel-scala.pdf
 
camel-scala.pdf
camel-scala.pdfcamel-scala.pdf
camel-scala.pdf
 
camel-scala.pdf
camel-scala.pdfcamel-scala.pdf
camel-scala.pdf
 
camel-scala.pdf
camel-scala.pdfcamel-scala.pdf
camel-scala.pdf
 
Developing a new Scala DSL for Apache Camel
Developing a new Scala DSL for Apache CamelDeveloping a new Scala DSL for Apache Camel
Developing a new Scala DSL for Apache Camel
 
Scala - core features
Scala - core featuresScala - core features
Scala - core features
 
Scilab: Computing Tool For Engineers
Scilab: Computing Tool For EngineersScilab: Computing Tool For Engineers
Scilab: Computing Tool For Engineers
 
Introduction to MATLAB
Introduction to MATLABIntroduction to MATLAB
Introduction to MATLAB
 
Two Days workshop on MATLAB
Two Days workshop on MATLABTwo Days workshop on MATLAB
Two Days workshop on MATLAB
 
Debugging and Profiling C++ Template Metaprograms
Debugging and Profiling C++ Template MetaprogramsDebugging and Profiling C++ Template Metaprograms
Debugging and Profiling C++ Template Metaprograms
 
Porting R Models into Scala Spark
Porting R Models into Scala SparkPorting R Models into Scala Spark
Porting R Models into Scala Spark
 
Programming in Scala: Notes
Programming in Scala: NotesProgramming in Scala: Notes
Programming in Scala: Notes
 

Recently uploaded

weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
Pratik Pawar
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
zwunae
 
Forklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella PartsForklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella Parts
Intella Parts
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation & Control
 
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdfGoverning Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
WENKENLI1
 
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
ssuser7dcef0
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
gdsczhcet
 
The Role of Electrical and Electronics Engineers in IOT Technology.pdf
The Role of Electrical and Electronics Engineers in IOT Technology.pdfThe Role of Electrical and Electronics Engineers in IOT Technology.pdf
The Role of Electrical and Electronics Engineers in IOT Technology.pdf
Nettur Technical Training Foundation
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
Kamal Acharya
 
Understanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine LearningUnderstanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine Learning
SUTEJAS
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
VENKATESHvenky89705
 
14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application
SyedAbiiAzazi1
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
ydteq
 
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdfTutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
aqil azizi
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
TeeVichai
 
PPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testingPPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testing
anoopmanoharan2
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
JoytuBarua2
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
fxintegritypublishin
 
Fundamentals of Induction Motor Drives.pptx
Fundamentals of Induction Motor Drives.pptxFundamentals of Induction Motor Drives.pptx
Fundamentals of Induction Motor Drives.pptx
manasideore6
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
Kamal Acharya
 

Recently uploaded (20)

weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
 
Forklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella PartsForklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella Parts
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
 
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdfGoverning Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
 
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
 
The Role of Electrical and Electronics Engineers in IOT Technology.pdf
The Role of Electrical and Electronics Engineers in IOT Technology.pdfThe Role of Electrical and Electronics Engineers in IOT Technology.pdf
The Role of Electrical and Electronics Engineers in IOT Technology.pdf
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
 
Understanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine LearningUnderstanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine Learning
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
 
14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
 
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdfTutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
 
PPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testingPPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testing
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
 
Fundamentals of Induction Motor Drives.pptx
Fundamentals of Induction Motor Drives.pptxFundamentals of Induction Motor Drives.pptx
Fundamentals of Induction Motor Drives.pptx
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
 

Codemotion akka voló sobre el nido del future

  • 1. MADRID · NOV 27-28 · 2015 Scala Programming @ Madrid Akka voló sobre el nido del Future Javier Santos David Vallejo
  • 2. MADRID · NOV 27-28 · 2015 Scala Programming @ Madrid About us David Vallejo @dvnavarro « It’s not a bug – it’s an undocumented feature.» Anonymous Javier Santos @jpaniego «Hay dos formas de programar sin errores; solo la tercera funciona» Alan J Perlis
  • 3. MADRID · NOV 27-28 · 2015 Scala Programming @ Madrid Introduction: A functional world ● Purely functional: whole world could be implemented in a single functional line ● Functional features ○ Robust ○ Debuggable ○ Predictable ○ Pluggable
  • 4. MADRID · NOV 27-28 · 2015 Scala Programming @ Madrid Introduction: A functional world ● Example type Context = (Input,Output,Error) type Action = Context => (Context,Event) def main( actions: Iterable[Action], context: Context):(Context,Seq[Event]) = { ((context,Seq.empty[Event]) /: actions) { case ((context,events),action) => action.apply(context) match { case (context,event) => (context, events :+ event) } } }
  • 5. MADRID · NOV 27-28 · 2015 Scala Programming @ Madrid
  • 6. MADRID · NOV 27-28 · 2015 Scala Programming @ Madrid Introduction: A functional world ● Problem? World actions are not precalculated. What happens to I/O? ● World can be considered as ○ asynchronous: Things may happen at same time ○ reactive: Things may happen due to ■ actions: that trigger … ■ ...events: action consequences.
  • 7. MADRID · NOV 27-28 · 2015 Scala Programming @ Madrid Introduction: Runnable & Callable ● java.lang.Runnable trait Runnable { def run(): Unit } ● java.util.concurrent.Callable trait Callable[V] { def call(): V }
  • 8. MADRID · NOV 27-28 · 2015 Scala Programming @ Madrid Introduction: Threads ● Scala’s concurrency model is built on Java’s ● java.lang.Thread val myThread = new Thread(new Runnable { def run(){ println(“hi”) } } myThread.start() ● Thread improvements (ExecutorService ~ Thread pool) ● Anyway, Threads abstraction level is too low
  • 9. MADRID · NOV 27-28 · 2015 Scala Programming @ Madrid What about Scala and threads?
  • 10. MADRID · NOV 27-28 · 2015 Scala Programming @ Madrid Future: Overview ● By default, non-blocking operations ● They will hold a T value at some point ● So a future may be uncompleted(it has no value yet) or completed ● Completion will be treated as a scala.util.Try value It will have two possible values: ○ Success(t: T) ○ Failure(t: Throwable)
  • 11. MADRID · NOV 27-28 · 2015 Scala Programming @ Madrid Future: Overview ● Future example import scala.concurrent._ import ExecutionContext.Implicits.global val firstPrimeNumbers: Future[List[Int]] = Future { List(1,2,3,5,7,11,13) //what if 'calculateFirstPrimeNumbers(100000000)'… } res0: Future[List[Int]]
  • 12. MADRID · NOV 27-28 · 2015 Scala Programming @ Madrid Future: Overview ● Failing Future example import scala.concurrent._ import ExecutionContext.Implicits.global val thisWillFail: Future[Int] = Future(2 / 0) res0: Future[Int]
  • 13. MADRID · NOV 27-28 · 2015 Scala Programming @ Madrid Future: ExecutionContext ● A future, once it’s completed, it never changes of value ● An ExecutionContext ○ executes tasks submitted to them. ○ They can be seen as thread pools. ○ Most of future ops require an implicit ExecutionContext.
  • 14. MADRID · NOV 27-28 · 2015 Scala Programming @ Madrid Future: Expecting results ● Expecting results. ○ Blocker way (discouraged but sometimes mandatory). ○ Non-blocker way: using callbacks
  • 15. MADRID · NOV 27-28 · 2015 Scala Programming @ Madrid Future: Blocking - Await ● Blocking: Await.result / Await.ready import scala.concurrent._ import scala.concurrent.duration._ import scala.concurrent.ExecutionContext.Implicits.global val f: Future[Int] = Future{ Thread.sleep(10000) 2 } println(Await.result(f,12.seconds)) //2
  • 16. MADRID · NOV 27-28 · 2015 Scala Programming @ Madrid Future: Blocking - Await ● Blocking: Await (Problem: Not enough time) import scala.concurrent._ import scala.concurrent.duration._ import scala.concurrent.ExecutionContext.Implicits.global val f: Future[Int] = Future{ Thread.sleep(10000) 2 } println(Await.result(f,5.seconds)) java.util.concurrent.TimeoutException: Futures timed out after [5 seconds]
  • 17. MADRID · NOV 27-28 · 2015 Scala Programming @ Madrid Future: Non-blocking - Callbacks ● Non-Blocking: callbacks import scala.concurrent._ import scala.concurrent.ExecutionContext.Implicits.global val f: Future[Int] = Future{ Thread.sleep(10000) 2 } f.onComplete( n => println(n) ) //at some point, “Success(2)” will appear Non-blocking
  • 18. MADRID · NOV 27-28 · 2015 Scala Programming @ Madrid Future: Callbacks ● Callbacks will be executed asynchronously when future is completed ● type Callback = Try[T] => Unit ● Try[T] ~ Either[Throwable,T] ○ Left(throwable) ~ Failure(throwable) ○ Right(t) ~ Success(t)
  • 19. MADRID · NOV 27-28 · 2015 Scala Programming @ Madrid Future: Callbacks ● onComplete f.onComplete( (t: Try[Int]) => println(t) ) //Success(2) ● onSuccess f.onSuccess( n => println(n) ) //2 ● onFailure f.onFailure( throwable => println(throwable.getMessage) ) //it will never print an error (because it equals Success(2))
  • 20. MADRID · NOV 27-28 · 2015 Scala Programming @ Madrid Future: Operations ● map def getFirstMillionOfPrimes(): Future[List[Int]] = ??? getFirstMillionOfPrimes().map( (list: List[Int]) => list.head) res0: Future[Int]
  • 21. MADRID · NOV 27-28 · 2015 Scala Programming @ Madrid Future: Operations ● flatMap def getFirstMillionOfPrimes(): Future[List[Int]] = ??? def concatenate(l: List[Int]): Future[String] = ??? getFirstMillionOfPrimes().flatMap( (list: List[Int]) => concatenate(list)) res0: Future[String]
  • 22. MADRID · NOV 27-28 · 2015 Scala Programming @ Madrid Future: Monad behavior ● Composition ○ Future is like a monad ■ Point Function: Future.apply ■ Bind Function: flatMap ■ Some math properties and so... ○ Since Future has map,flatMap,filter methods; it can be composed easily in a for-comprehension
  • 23. MADRID · NOV 27-28 · 2015 Scala Programming @ Madrid
  • 24. MADRID · NOV 27-28 · 2015 Scala Programming @ Madrid Future: Composition ● Problem var result: String = “” val f1: Future[Unit] = Future{ result += “Hi ” } val f2: Future[Unit] = Future{ result += “ everyone” } ● result value? “Hi everyone”? “ everyoneHi”?
  • 25. MADRID · NOV 27-28 · 2015 Scala Programming @ Madrid
  • 26. MADRID · NOV 27-28 · 2015 Scala Programming @ Madrid Future: Composition ● for-comprehension is your friend for { primes <- getFirstMillionPrimes() primesString <- concatenate(primes) } yield primesString res0: Future[String] Future[List[Int]] Future[String]
  • 27. MADRID · NOV 27-28 · 2015 Scala Programming @ Madrid Future: Recovering from failure ● recover val f: Future[Int] = Future{ 1 / 0 }.recover{ case e: ArithmeticException => 0 }
  • 28. MADRID · NOV 27-28 · 2015 Scala Programming @ Madrid Future: Recovering from failure ● recoverWith val f: Future[Int] = Future{ 1 / 0 }.recoverWith{ case e: ArithmeticException => Future(0) }
  • 29. MADRID · NOV 27-28 · 2015 Scala Programming @ Madrid Future: Recovering from failure ● fallbackTo val f1: Future[Int] = Future{ 1 / 0 } val f2: Future[Int] = Future(0) val f = f1 fallbackTo f2
  • 30. MADRID · NOV 27-28 · 2015 Scala Programming @ Madrid Promise: Overview ● Futures can be created by ○ Future.apply ○ Promises ● You can think about it like ○ Future ~ Read future value ○ Promise ~ Write future value ● Promises are single-assigned (just once. Immutable as futures)
  • 31. MADRID · NOV 27-28 · 2015 Scala Programming @ Madrid Promise: Baggage & claim Menu order Menu Being Cooked Ticket Menu ready
  • 32. MADRID · NOV 27-28 · 2015 Scala Programming @ Madrid Promise: Baggage & claim Begin completion Future[T] p.success or p.failure Try[T] Promise[T]
  • 33. MADRID · NOV 27-28 · 2015 Scala Programming @ Madrid Promise: example val r: T = produceSomething() p success r doSomethingElse() startDoingSomething() f onSuccess { case r: T => handleResult() } val p = promise[T] val f = p.future Producer Consumer
  • 34. MADRID · NOV 27-28 · 2015 Scala Programming @ Madrid Promise: completion ● complete val p = promise[Int] p.complete(Try(2)) ● completeWith val p = promise[Int] p.completeWith(Future(2))
  • 35. MADRID · NOV 27-28 · 2015 Scala Programming @ Madrid Future alternatives ● Scalaz futures ● Scala’s async library
  • 36. MADRID · NOV 27-28 · 2015 Scala Programming @ Madrid Tones of slides and however... Futures/Promises Akka actors
  • 37. MADRID · NOV 27-28 · 2015 Scala Programming @ Madrid
  • 38. MADRID · NOV 27-28 · 2015 Scala Programming @ Madrid Akka: main concepts ● Actors, actors everywhere ● Asynchronous messages ● Event-driven processes ● Distributed systems
  • 39. MADRID · NOV 27-28 · 2015 Scala Programming @ Madrid Akka: Actors ● Black box ● State without race condition ● Messages to update the state
  • 40. MADRID · NOV 27-28 · 2015 Scala Programming @ Madrid Akka: Actors class MyFirstActor extends Actor { override def receive = { case _ => println("Hello World!") } }
  • 41. MADRID · NOV 27-28 · 2015 Scala Programming @ Madrid Akka: Send a message ● Tell message actor ! "Hi" ● Ask message actor ? "Are you there"
  • 42. MADRID · NOV 27-28 · 2015 Scala Programming @ Madrid Akka: Ask pattern implicit val timeout = Timeout(5 seconds) val f: Future[String] = (actorRef ? AreYouThere).mapTo[String]
  • 43. MADRID · NOV 27-28 · 2015 Scala Programming @ Madrid Akka: An example
  • 44. MADRID · NOV 27-28 · 2015 Scala Programming @ Madrid Akka: Services user service contact service address service System GetUser(id) GetContacts(name) GetAddress(name) Option[User] List[Contact] Address UserInfo
  • 45. MADRID · NOV 27-28 · 2015 Scala Programming @ Madrid Akka: Ask Pattern & For Comprehension class UserServiceActor extends Actor { val users: Map[String, User] = Map("1" -> User("John"), "2" -> User("Jack")) override def receive = { case GetUser(userId: String) => sender ! users.get(userId) } }
  • 46. MADRID · NOV 27-28 · 2015 Scala Programming @ Madrid Akka: Ask Pattern & For Comprehension def getInfo(userId: String): Future[UserInfo] = for { Some(user) <- (usersActor ? GetUser(userId)) .mapTo[Option[User]] contacts <- (contactsActor.?(GetContacts(user.name)) (Timeout(5 seconds),context.self)) .mapTo[List[Contact]] address <- (addressesActor ? GetAddress(user.name)) .mapTo[Address] } yield UserInfo(user, contacts, address)
  • 47. MADRID · NOV 27-28 · 2015 Scala Programming @ Madrid
  • 48. MADRID · NOV 27-28 · 2015 Scala Programming @ Madrid scalera.es @scalerablog
  • 49. MADRID · NOV 27-28 · 2015 Scala Programming @ Madrid
  • 50. MADRID · NOV 27-28 · 2015 Scala Programming @ Madrid Primeros pasos con Akka: Olvídate de los threads 27 NOVEMBER TRACK D 18:00
  • 51. MADRID · NOV 27-28 · 2015 Scala Programming @ Madrid Caminando de Java a Scala en menos de 2 horas 28 NOVEMBER TRACK B 9:30
  • 52. MADRID · NOV 27-28 · 2015 Scala Programming @ Madrid
  • 53. MADRID · NOV 27-28 · 2015 Scala Programming @ Madrid Akka voló sobre el nido del Future Javier Santos David Vallejo