SlideShare uma empresa Scribd logo
1 de 38
Baixar para ler offline
Asynchronous Scala
April 2015, Javier Santos
Promising futures...
Javier Santos Paniego
Scala Developer
jsantos@stratio.com
CONTACT
INTRODUCTION
• Functional World
• Runnable/Callable
• Threads
1 2 3FUTURES
• Completion
• ExecutionContext
• Callbacks
• Future monad
• Composition
• Recovery
PROMISES
• Baggage & Claim
• Completion
INDEX
Introduction
Introduction
Asynchronous Scala: Promising futures
● Purely functional: whole world could be implemented in a single
functional line
● Functional features
○ Robust
○ Debuggable
○ Predictable
○ Pluggable
Introduction
A functional world
Asynchronous Scala: Promising futures
● 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),actions) =>
action.apply(context) match {
case (context,event) => (context, events :+ event)
}
}
}
Introduction
A functional world
Asynchronous Scala: Promising futures
● 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.
Introduction
A functional world
Asynchronous Scala: Promising futures
● java.lang.Runnable
trait Runnable {
def run(): Unit
}
● java.util.concurrent.Callable
trait Callable[V] {
def call(): V
}
Introduction
Runnable & Callable
Asynchronous Scala: Promising futures
● Scala’s concurrency model is built on Java’s
● java.lang.Thread
val myThread = new Thread(new Runnable {
def run(){
println(“hi”)
}
}
myThread.start()
Introduction
Threads
Asynchronous Scala: Promising futures
● Thread improvements
○ ExecutorService (obtained from static Executors) allows using
thread policies (like threading pools)
val pool: ExecutorService = Executors.newFixedThreadPool(poolSize)
pool.execute(new Runnable{
def run(){
println(“I’m handling a request”)
}
})
○ Anyway, Threads abstraction level is too low
Introduction
Thread policies
Futures
Futures
Asynchronous Scala: Promising futures
● 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)
Futures
Overview
Asynchronous Scala: Promising futures
● Successfully completion 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(100000)'…
}
res0: Future[List[Int]]
Futures
Success on completion
Asynchronous Scala: Promising futures
● Failure completion example
import scala.concurrent._
import ExecutionContext.Implicits.global
val thisWillFail: Future[Int] = Future(2 / 0)
res0: Future[Int]
Futures
Failure on completion
Asynchronous Scala: Promising futures
● 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.
Futures
ExecutionContext
Asynchronous Scala: Promising futures
● Expecting results.
○ Blocker way (discouraged but sometimes mandatory).
○ Non-blocker way: using callbacks
Futures
Expecting results
Asynchronous Scala: Promising futures
● 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
Futures
Blocking: Await
Asynchronous Scala: Promising futures
● 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]
Futures
Blocking: Await problem
Asynchronous Scala: Promising futures
● Non-Blocking: callbacks
import scala.concurrent._
import scala.concurrent.duration._
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
Futures
Non-blocking: Callbacks
Non-blocking
Asynchronous Scala: Promising futures
● Callbacks will be executed asynchronously when future is
completed
● Try[T] => U
● Try[T] ~ Either[Throwable,T]
○ Left(throwable) ~ Failure(throwable)
○ Right(t) ~ Success(t)
Futures
Callbacks
Asynchronous Scala: Promising futures
● onComplete
f.onComplete( (t: Try[Int]) => println(n) )
//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))
Futures
Callbacks
Asynchronous Scala: Promising futures
● Composition
○ Future is a monad
■ Type Constructor: T => Future[T]
■ Unit Function: Future.apply
■ Bind Function: flatMap
○ Since Future has map,flatMap,filter methods; it can be composed
easily in a for-comprehension
Futures
Monad behavior
Asynchronous Scala: Promising futures
Futures
Monad behavior
Asynchronous Scala: Promising futures
● map
def getFirstMillionOfPrimes(): Future[List[Int]] = ???
getFirstMillionOfPrimes().map(
(list: List[Int]) => list.head)
res0: Future[Int]
Futures
Monad behavior
Asynchronous Scala: Promising futures
● flatMap
def getFirstMillionOfPrimes(): Future[List[Int]] = ???
def concatenate(l: List[Int]): Future[String] = ???
getFirstMillionOfPrimes().flatMap((list: List[Int]) => concatenate(list))
res0: Future[String]
Futures
Monad behavior
Asynchronous Scala: Promising futures
● Problem
var result: String = “”
val f1: Future[Unit] = Future{result += “Hi ”}
val f2: Future[Unit] = Future{result += “ everyone”}
● result value?
Futures
Composition
Asynchronous Scala: Promising futures
● for-comprehension is your friend
for {
primes <- getFirstMillionPrimes()
primesString <- concatenate(primes)
} yield primes
res0: Future[String]
Futures
Composition
Future[List[Int]]
Future[String]
Asynchronous Scala: Promising futures
● recover
val f: Future[Int] = Future{
1 / 0
}.recover{
case e: ArithmeticException => 0
}
Futures
Recovering from failure
Asynchronous Scala: Promising futures
● recoverWith
val f: Future[Int] = Future{
1 / 0
}.recoverWith{
case e: ArithmeticException => Future(0)
}
Futures
Recovering from failure
Asynchronous Scala: Promising futures
● fallbackTo
val f1: Future[Int] = Future{
1 / 0
}
val f2: Future[Int] = Future(0)
val f = f1 fallbackTo f2
Futures
Recovering from failure
Promises
Promises
Asynchronous Scala: Promising futures
● 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)
Promises
Overview
Asynchronous Scala: Promising futures
Promises
Baggage & claim pattern
Menu
order
Menu
Being
Cooked
Ticket
Menu
Ready
Asynchronous Scala: Promising futures
Promises
Baggage & claim pattern
Promise[T]
Begin
completion
Future[T]
p.success
or
p.failure
Try[T]
Asynchronous Scala: Promising futures
Promises
Example
val producer = future {
val r: T = produceSomething()
p success r
continueDoingSomethingUnrelated()
}
val consumer = future {
startDoingSomething()
f onSuccess {
case r: T => handleResult()
}
}
val p = promise[T]
val f = p.future
Asynchronous Scala: Promising futures
● complete
val p: Promise[Int]
p.complete(Try(2))
● completeWith
val p: Promise[Int]
p.completeWith(Future(2))
Promises
Overview
Asynchronous Scala: Promising futures
Finished...
...for today
Futures/Promises
Akka actors
Still interested?
● Scala school (Twitter)
● Reactive Design Patterns, Roland
Kuhn and Jamie Allen
● Scala-lang docs: Futures and
promises
● Akka doc - Futures
Introduction to Asynchronous scala

Mais conteúdo relacionado

Mais procurados

React Development with the MERN Stack
React Development with the MERN StackReact Development with the MERN Stack
React Development with the MERN StackTroy Miles
 
Composable and streamable Play apps
Composable and streamable Play appsComposable and streamable Play apps
Composable and streamable Play appsYevgeniy Brikman
 
Play + scala + reactive mongo
Play + scala + reactive mongoPlay + scala + reactive mongo
Play + scala + reactive mongoMax Kremer
 
Concurrency in Scala - the Akka way
Concurrency in Scala - the Akka wayConcurrency in Scala - the Akka way
Concurrency in Scala - the Akka wayYardena Meymann
 
3 things you must know to think reactive - Geecon Kraków 2015
3 things you must know to think reactive - Geecon Kraków 20153 things you must know to think reactive - Geecon Kraków 2015
3 things you must know to think reactive - Geecon Kraków 2015Manuel Bernhardt
 
The dark side of Akka and the remedy
The dark side of Akka and the remedyThe dark side of Akka and the remedy
The dark side of Akka and the remedykrivachy
 
The Why and How of Scala at Twitter
The Why and How of Scala at TwitterThe Why and How of Scala at Twitter
The Why and How of Scala at TwitterAlex Payne
 
Mobile Open Day: React Native: Crossplatform fast dive
Mobile Open Day: React Native: Crossplatform fast diveMobile Open Day: React Native: Crossplatform fast dive
Mobile Open Day: React Native: Crossplatform fast diveepamspb
 
Fullstack Conference - Proxies before proxies: The hidden gems of Javascript...
Fullstack Conference -  Proxies before proxies: The hidden gems of Javascript...Fullstack Conference -  Proxies before proxies: The hidden gems of Javascript...
Fullstack Conference - Proxies before proxies: The hidden gems of Javascript...Tim Chaplin
 
React Native One Day
React Native One DayReact Native One Day
React Native One DayTroy Miles
 
Async - react, don't wait - PingConf
Async - react, don't wait - PingConfAsync - react, don't wait - PingConf
Async - react, don't wait - PingConfJohan Andrén
 
BOF2644 Developing Java EE 7 Scala apps
BOF2644 Developing Java EE 7 Scala appsBOF2644 Developing Java EE 7 Scala apps
BOF2644 Developing Java EE 7 Scala appsPeter Pilgrim
 
Intro to React
Intro to ReactIntro to React
Intro to ReactTroy Miles
 
Java Play RESTful ebean
Java Play RESTful ebeanJava Play RESTful ebean
Java Play RESTful ebeanFaren faren
 
React Native Evening
React Native EveningReact Native Evening
React Native EveningTroy Miles
 
Java Play Restful JPA
Java Play Restful JPAJava Play Restful JPA
Java Play Restful JPAFaren faren
 
Akka Cluster in Java - JCConf 2015
Akka Cluster in Java - JCConf 2015Akka Cluster in Java - JCConf 2015
Akka Cluster in Java - JCConf 2015Jiayun Zhou
 
QCon 2015 Scala for the Enterprise: Get FuNkEd Up on the JVM
QCon 2015 Scala for the Enterprise: Get FuNkEd Up on the JVMQCon 2015 Scala for the Enterprise: Get FuNkEd Up on the JVM
QCon 2015 Scala for the Enterprise: Get FuNkEd Up on the JVMPeter Pilgrim
 

Mais procurados (20)

React Development with the MERN Stack
React Development with the MERN StackReact Development with the MERN Stack
React Development with the MERN Stack
 
Composable and streamable Play apps
Composable and streamable Play appsComposable and streamable Play apps
Composable and streamable Play apps
 
Play + scala + reactive mongo
Play + scala + reactive mongoPlay + scala + reactive mongo
Play + scala + reactive mongo
 
Concurrency in Scala - the Akka way
Concurrency in Scala - the Akka wayConcurrency in Scala - the Akka way
Concurrency in Scala - the Akka way
 
3 things you must know to think reactive - Geecon Kraków 2015
3 things you must know to think reactive - Geecon Kraków 20153 things you must know to think reactive - Geecon Kraków 2015
3 things you must know to think reactive - Geecon Kraków 2015
 
The dark side of Akka and the remedy
The dark side of Akka and the remedyThe dark side of Akka and the remedy
The dark side of Akka and the remedy
 
The Why and How of Scala at Twitter
The Why and How of Scala at TwitterThe Why and How of Scala at Twitter
The Why and How of Scala at Twitter
 
Mobile Open Day: React Native: Crossplatform fast dive
Mobile Open Day: React Native: Crossplatform fast diveMobile Open Day: React Native: Crossplatform fast dive
Mobile Open Day: React Native: Crossplatform fast dive
 
Fullstack Conference - Proxies before proxies: The hidden gems of Javascript...
Fullstack Conference -  Proxies before proxies: The hidden gems of Javascript...Fullstack Conference -  Proxies before proxies: The hidden gems of Javascript...
Fullstack Conference - Proxies before proxies: The hidden gems of Javascript...
 
Async fun
Async funAsync fun
Async fun
 
React Native One Day
React Native One DayReact Native One Day
React Native One Day
 
Async - react, don't wait - PingConf
Async - react, don't wait - PingConfAsync - react, don't wait - PingConf
Async - react, don't wait - PingConf
 
BOF2644 Developing Java EE 7 Scala apps
BOF2644 Developing Java EE 7 Scala appsBOF2644 Developing Java EE 7 Scala apps
BOF2644 Developing Java EE 7 Scala apps
 
Java 8 concurrency abstractions
Java 8 concurrency abstractionsJava 8 concurrency abstractions
Java 8 concurrency abstractions
 
Intro to React
Intro to ReactIntro to React
Intro to React
 
Java Play RESTful ebean
Java Play RESTful ebeanJava Play RESTful ebean
Java Play RESTful ebean
 
React Native Evening
React Native EveningReact Native Evening
React Native Evening
 
Java Play Restful JPA
Java Play Restful JPAJava Play Restful JPA
Java Play Restful JPA
 
Akka Cluster in Java - JCConf 2015
Akka Cluster in Java - JCConf 2015Akka Cluster in Java - JCConf 2015
Akka Cluster in Java - JCConf 2015
 
QCon 2015 Scala for the Enterprise: Get FuNkEd Up on the JVM
QCon 2015 Scala for the Enterprise: Get FuNkEd Up on the JVMQCon 2015 Scala for the Enterprise: Get FuNkEd Up on the JVM
QCon 2015 Scala for the Enterprise: Get FuNkEd Up on the JVM
 

Destaque

Spark Streaming @ Berlin Apache Spark Meetup, March 2015
Spark Streaming @ Berlin Apache Spark Meetup, March 2015Spark Streaming @ Berlin Apache Spark Meetup, March 2015
Spark Streaming @ Berlin Apache Spark Meetup, March 2015Stratio
 
Codemotion 2015 - Akka voló sobre el nido del future
Codemotion 2015 - Akka voló sobre el nido del futureCodemotion 2015 - Akka voló sobre el nido del future
Codemotion 2015 - Akka voló sobre el nido del futurescalerablog
 
Functional programming in scala
Functional programming in scalaFunctional programming in scala
Functional programming in scalaStratio
 
Primeros pasos con Spark - Spark Meetup Madrid 30-09-2014
Primeros pasos con Spark - Spark Meetup Madrid 30-09-2014Primeros pasos con Spark - Spark Meetup Madrid 30-09-2014
Primeros pasos con Spark - Spark Meetup Madrid 30-09-2014Stratio
 
Stratio's Cassandra Lucene index: Geospatial use cases - Big Data Spain 2016
Stratio's Cassandra Lucene index: Geospatial use cases - Big Data Spain 2016Stratio's Cassandra Lucene index: Geospatial use cases - Big Data Spain 2016
Stratio's Cassandra Lucene index: Geospatial use cases - Big Data Spain 2016Stratio
 
Apache Spark & Cassandra use case at Telefónica Cbs by Antonio Alcacer
Apache Spark & Cassandra use case at Telefónica Cbs by Antonio AlcacerApache Spark & Cassandra use case at Telefónica Cbs by Antonio Alcacer
Apache Spark & Cassandra use case at Telefónica Cbs by Antonio AlcacerStratio
 
Multiplaform Solution for Graph Datasources
Multiplaform Solution for Graph DatasourcesMultiplaform Solution for Graph Datasources
Multiplaform Solution for Graph DatasourcesStratio
 
Lunch&Learn: Combinación de modelos
Lunch&Learn: Combinación de modelosLunch&Learn: Combinación de modelos
Lunch&Learn: Combinación de modelosStratio
 
Stratio platform overview v4.1
Stratio platform overview v4.1Stratio platform overview v4.1
Stratio platform overview v4.1Stratio
 
[Strata] Sparkta
[Strata] Sparkta[Strata] Sparkta
[Strata] SparktaStratio
 
Stratio CrossData: an efficient distributed datahub with batch and streaming ...
Stratio CrossData: an efficient distributed datahub with batch and streaming ...Stratio CrossData: an efficient distributed datahub with batch and streaming ...
Stratio CrossData: an efficient distributed datahub with batch and streaming ...Stratio
 
Distributed Logistic Model Trees
Distributed Logistic Model TreesDistributed Logistic Model Trees
Distributed Logistic Model TreesStratio
 
On-the-fly ETL con EFK: ElasticSearch, Flume, Kibana
On-the-fly ETL con EFK: ElasticSearch, Flume, KibanaOn-the-fly ETL con EFK: ElasticSearch, Flume, Kibana
On-the-fly ETL con EFK: ElasticSearch, Flume, KibanaStratio
 
[Spark meetup] Spark Streaming Overview
[Spark meetup] Spark Streaming Overview[Spark meetup] Spark Streaming Overview
[Spark meetup] Spark Streaming OverviewStratio
 
Meetup: Spark + Kerberos
Meetup: Spark + KerberosMeetup: Spark + Kerberos
Meetup: Spark + KerberosStratio
 

Destaque (20)

Spark Streaming @ Berlin Apache Spark Meetup, March 2015
Spark Streaming @ Berlin Apache Spark Meetup, March 2015Spark Streaming @ Berlin Apache Spark Meetup, March 2015
Spark Streaming @ Berlin Apache Spark Meetup, March 2015
 
Scala @ Real Life Codemotion 2014
Scala @ Real Life Codemotion 2014Scala @ Real Life Codemotion 2014
Scala @ Real Life Codemotion 2014
 
Scala@real life
Scala@real lifeScala@real life
Scala@real life
 
Codemotion 2015 - Akka voló sobre el nido del future
Codemotion 2015 - Akka voló sobre el nido del futureCodemotion 2015 - Akka voló sobre el nido del future
Codemotion 2015 - Akka voló sobre el nido del future
 
Introducción a akka
Introducción a akkaIntroducción a akka
Introducción a akka
 
Codemotion 2014 Scala @real life
Codemotion 2014 Scala @real lifeCodemotion 2014 Scala @real life
Codemotion 2014 Scala @real life
 
Scala for dummies
Scala for dummiesScala for dummies
Scala for dummies
 
Functional programming in scala
Functional programming in scalaFunctional programming in scala
Functional programming in scala
 
Primeros pasos con Spark - Spark Meetup Madrid 30-09-2014
Primeros pasos con Spark - Spark Meetup Madrid 30-09-2014Primeros pasos con Spark - Spark Meetup Madrid 30-09-2014
Primeros pasos con Spark - Spark Meetup Madrid 30-09-2014
 
Stratio's Cassandra Lucene index: Geospatial use cases - Big Data Spain 2016
Stratio's Cassandra Lucene index: Geospatial use cases - Big Data Spain 2016Stratio's Cassandra Lucene index: Geospatial use cases - Big Data Spain 2016
Stratio's Cassandra Lucene index: Geospatial use cases - Big Data Spain 2016
 
Apache Spark & Cassandra use case at Telefónica Cbs by Antonio Alcacer
Apache Spark & Cassandra use case at Telefónica Cbs by Antonio AlcacerApache Spark & Cassandra use case at Telefónica Cbs by Antonio Alcacer
Apache Spark & Cassandra use case at Telefónica Cbs by Antonio Alcacer
 
Multiplaform Solution for Graph Datasources
Multiplaform Solution for Graph DatasourcesMultiplaform Solution for Graph Datasources
Multiplaform Solution for Graph Datasources
 
Lunch&Learn: Combinación de modelos
Lunch&Learn: Combinación de modelosLunch&Learn: Combinación de modelos
Lunch&Learn: Combinación de modelos
 
Stratio platform overview v4.1
Stratio platform overview v4.1Stratio platform overview v4.1
Stratio platform overview v4.1
 
[Strata] Sparkta
[Strata] Sparkta[Strata] Sparkta
[Strata] Sparkta
 
Stratio CrossData: an efficient distributed datahub with batch and streaming ...
Stratio CrossData: an efficient distributed datahub with batch and streaming ...Stratio CrossData: an efficient distributed datahub with batch and streaming ...
Stratio CrossData: an efficient distributed datahub with batch and streaming ...
 
Distributed Logistic Model Trees
Distributed Logistic Model TreesDistributed Logistic Model Trees
Distributed Logistic Model Trees
 
On-the-fly ETL con EFK: ElasticSearch, Flume, Kibana
On-the-fly ETL con EFK: ElasticSearch, Flume, KibanaOn-the-fly ETL con EFK: ElasticSearch, Flume, Kibana
On-the-fly ETL con EFK: ElasticSearch, Flume, Kibana
 
[Spark meetup] Spark Streaming Overview
[Spark meetup] Spark Streaming Overview[Spark meetup] Spark Streaming Overview
[Spark meetup] Spark Streaming Overview
 
Meetup: Spark + Kerberos
Meetup: Spark + KerberosMeetup: Spark + Kerberos
Meetup: Spark + Kerberos
 

Semelhante a Introduction to Asynchronous scala

The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)jeffz
 
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)jeffz
 
Railroading into Scala
Railroading into ScalaRailroading into Scala
Railroading into ScalaNehal Shah
 
From Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risksFrom Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risksSeniorDevOnly
 
pure-functional-programming.pdf
pure-functional-programming.pdfpure-functional-programming.pdf
pure-functional-programming.pdfPuneetChaturvedi23
 
Reactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwiftReactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwiftFlorent Pillet
 
Introduction to meta-programming in scala
Introduction to meta-programming in scalaIntroduction to meta-programming in scala
Introduction to meta-programming in scalaAlessandro Marrella
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)Pavlo Baron
 
Introduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoMuhammad Abdullah
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойSigma Software
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scalapramode_ce
 
Talk - Query monad
Talk - Query monad Talk - Query monad
Talk - Query monad Fabernovel
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()daewon jeong
 
Functional programming with Scala
Functional programming with ScalaFunctional programming with Scala
Functional programming with ScalaNeelkanth Sachdeva
 
How to start functional programming (in Scala): Day1
How to start functional programming (in Scala): Day1How to start functional programming (in Scala): Day1
How to start functional programming (in Scala): Day1Taisuke Oe
 

Semelhante a Introduction to Asynchronous scala (20)

Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
 
The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)
 
Coding in Style
Coding in StyleCoding in Style
Coding in Style
 
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
 
Railroading into Scala
Railroading into ScalaRailroading into Scala
Railroading into Scala
 
From Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risksFrom Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risks
 
pure-functional-programming.pdf
pure-functional-programming.pdfpure-functional-programming.pdf
pure-functional-programming.pdf
 
Reactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwiftReactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwift
 
Introduction to meta-programming in scala
Introduction to meta-programming in scalaIntroduction to meta-programming in scala
Introduction to meta-programming in scala
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
 
Clojure intro
Clojure introClojure intro
Clojure intro
 
Introduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demo
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай Мозговой
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scala
 
JavaScript for real men
JavaScript for real menJavaScript for real men
JavaScript for real men
 
Scala coated JVM
Scala coated JVMScala coated JVM
Scala coated JVM
 
Talk - Query monad
Talk - Query monad Talk - Query monad
Talk - Query monad
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()
 
Functional programming with Scala
Functional programming with ScalaFunctional programming with Scala
Functional programming with Scala
 
How to start functional programming (in Scala): Day1
How to start functional programming (in Scala): Day1How to start functional programming (in Scala): Day1
How to start functional programming (in Scala): Day1
 

Mais de Stratio

Mesos Meetup - Building an enterprise-ready analytics and operational ecosyst...
Mesos Meetup - Building an enterprise-ready analytics and operational ecosyst...Mesos Meetup - Building an enterprise-ready analytics and operational ecosyst...
Mesos Meetup - Building an enterprise-ready analytics and operational ecosyst...Stratio
 
Can an intelligent system exist without awareness? BDS18
Can an intelligent system exist without awareness? BDS18Can an intelligent system exist without awareness? BDS18
Can an intelligent system exist without awareness? BDS18Stratio
 
Kafka and KSQL - Apache Kafka Meetup
Kafka and KSQL - Apache Kafka MeetupKafka and KSQL - Apache Kafka Meetup
Kafka and KSQL - Apache Kafka MeetupStratio
 
Wild Data - The Data Science Meetup
Wild Data - The Data Science MeetupWild Data - The Data Science Meetup
Wild Data - The Data Science MeetupStratio
 
Using Kafka on Event-driven Microservices Architectures - Apache Kafka Meetup
Using Kafka on Event-driven Microservices Architectures - Apache Kafka MeetupUsing Kafka on Event-driven Microservices Architectures - Apache Kafka Meetup
Using Kafka on Event-driven Microservices Architectures - Apache Kafka MeetupStratio
 
Ensemble methods in Machine Learning
Ensemble methods in Machine Learning Ensemble methods in Machine Learning
Ensemble methods in Machine Learning Stratio
 
Stratio Sparta 2.0
Stratio Sparta 2.0Stratio Sparta 2.0
Stratio Sparta 2.0Stratio
 
Big Data Security: Facing the challenge
Big Data Security: Facing the challengeBig Data Security: Facing the challenge
Big Data Security: Facing the challengeStratio
 
Operationalizing Big Data
Operationalizing Big DataOperationalizing Big Data
Operationalizing Big DataStratio
 
Artificial Intelligence on Data Centric Platform
Artificial Intelligence on Data Centric PlatformArtificial Intelligence on Data Centric Platform
Artificial Intelligence on Data Centric PlatformStratio
 
Introduction to Artificial Neural Networks
Introduction to Artificial Neural NetworksIntroduction to Artificial Neural Networks
Introduction to Artificial Neural NetworksStratio
 
“A Distributed Operational and Informational Technological Stack”
“A Distributed Operational and Informational Technological Stack” “A Distributed Operational and Informational Technological Stack”
“A Distributed Operational and Informational Technological Stack” Stratio
 
Meetup: Cómo monitorizar y optimizar procesos de Spark usando la Spark Web - ...
Meetup: Cómo monitorizar y optimizar procesos de Spark usando la Spark Web - ...Meetup: Cómo monitorizar y optimizar procesos de Spark usando la Spark Web - ...
Meetup: Cómo monitorizar y optimizar procesos de Spark usando la Spark Web - ...Stratio
 
Advanced search and Top-K queries in Cassandra
Advanced search and Top-K queries in CassandraAdvanced search and Top-K queries in Cassandra
Advanced search and Top-K queries in CassandraStratio
 
Why spark by Stratio - v.1.0
Why spark by Stratio - v.1.0Why spark by Stratio - v.1.0
Why spark by Stratio - v.1.0Stratio
 
Spark Summit - Stratio Streaming
Spark Summit - Stratio Streaming Spark Summit - Stratio Streaming
Spark Summit - Stratio Streaming Stratio
 

Mais de Stratio (16)

Mesos Meetup - Building an enterprise-ready analytics and operational ecosyst...
Mesos Meetup - Building an enterprise-ready analytics and operational ecosyst...Mesos Meetup - Building an enterprise-ready analytics and operational ecosyst...
Mesos Meetup - Building an enterprise-ready analytics and operational ecosyst...
 
Can an intelligent system exist without awareness? BDS18
Can an intelligent system exist without awareness? BDS18Can an intelligent system exist without awareness? BDS18
Can an intelligent system exist without awareness? BDS18
 
Kafka and KSQL - Apache Kafka Meetup
Kafka and KSQL - Apache Kafka MeetupKafka and KSQL - Apache Kafka Meetup
Kafka and KSQL - Apache Kafka Meetup
 
Wild Data - The Data Science Meetup
Wild Data - The Data Science MeetupWild Data - The Data Science Meetup
Wild Data - The Data Science Meetup
 
Using Kafka on Event-driven Microservices Architectures - Apache Kafka Meetup
Using Kafka on Event-driven Microservices Architectures - Apache Kafka MeetupUsing Kafka on Event-driven Microservices Architectures - Apache Kafka Meetup
Using Kafka on Event-driven Microservices Architectures - Apache Kafka Meetup
 
Ensemble methods in Machine Learning
Ensemble methods in Machine Learning Ensemble methods in Machine Learning
Ensemble methods in Machine Learning
 
Stratio Sparta 2.0
Stratio Sparta 2.0Stratio Sparta 2.0
Stratio Sparta 2.0
 
Big Data Security: Facing the challenge
Big Data Security: Facing the challengeBig Data Security: Facing the challenge
Big Data Security: Facing the challenge
 
Operationalizing Big Data
Operationalizing Big DataOperationalizing Big Data
Operationalizing Big Data
 
Artificial Intelligence on Data Centric Platform
Artificial Intelligence on Data Centric PlatformArtificial Intelligence on Data Centric Platform
Artificial Intelligence on Data Centric Platform
 
Introduction to Artificial Neural Networks
Introduction to Artificial Neural NetworksIntroduction to Artificial Neural Networks
Introduction to Artificial Neural Networks
 
“A Distributed Operational and Informational Technological Stack”
“A Distributed Operational and Informational Technological Stack” “A Distributed Operational and Informational Technological Stack”
“A Distributed Operational and Informational Technological Stack”
 
Meetup: Cómo monitorizar y optimizar procesos de Spark usando la Spark Web - ...
Meetup: Cómo monitorizar y optimizar procesos de Spark usando la Spark Web - ...Meetup: Cómo monitorizar y optimizar procesos de Spark usando la Spark Web - ...
Meetup: Cómo monitorizar y optimizar procesos de Spark usando la Spark Web - ...
 
Advanced search and Top-K queries in Cassandra
Advanced search and Top-K queries in CassandraAdvanced search and Top-K queries in Cassandra
Advanced search and Top-K queries in Cassandra
 
Why spark by Stratio - v.1.0
Why spark by Stratio - v.1.0Why spark by Stratio - v.1.0
Why spark by Stratio - v.1.0
 
Spark Summit - Stratio Streaming
Spark Summit - Stratio Streaming Spark Summit - Stratio Streaming
Spark Summit - Stratio Streaming
 

Último

introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfVishalKumarJha10
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfayushiqss
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park masabamasaba
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionOnePlan Solutions
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...kalichargn70th171
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedSector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedDelhi Call girls
 
Pharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodologyPharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodologyAnusha Are
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrainmasabamasaba
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456KiaraTiradoMicha
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfonteinmasabamasaba
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 

Último (20)

introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedSector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
 
Pharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodologyPharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodology
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 

Introduction to Asynchronous scala

  • 1. Asynchronous Scala April 2015, Javier Santos Promising futures...
  • 2. Javier Santos Paniego Scala Developer jsantos@stratio.com CONTACT INTRODUCTION • Functional World • Runnable/Callable • Threads 1 2 3FUTURES • Completion • ExecutionContext • Callbacks • Future monad • Composition • Recovery PROMISES • Baggage & Claim • Completion INDEX
  • 4. Asynchronous Scala: Promising futures ● Purely functional: whole world could be implemented in a single functional line ● Functional features ○ Robust ○ Debuggable ○ Predictable ○ Pluggable Introduction A functional world
  • 5. Asynchronous Scala: Promising futures ● 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),actions) => action.apply(context) match { case (context,event) => (context, events :+ event) } } } Introduction A functional world
  • 6. Asynchronous Scala: Promising futures ● 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. Introduction A functional world
  • 7. Asynchronous Scala: Promising futures ● java.lang.Runnable trait Runnable { def run(): Unit } ● java.util.concurrent.Callable trait Callable[V] { def call(): V } Introduction Runnable & Callable
  • 8. Asynchronous Scala: Promising futures ● Scala’s concurrency model is built on Java’s ● java.lang.Thread val myThread = new Thread(new Runnable { def run(){ println(“hi”) } } myThread.start() Introduction Threads
  • 9. Asynchronous Scala: Promising futures ● Thread improvements ○ ExecutorService (obtained from static Executors) allows using thread policies (like threading pools) val pool: ExecutorService = Executors.newFixedThreadPool(poolSize) pool.execute(new Runnable{ def run(){ println(“I’m handling a request”) } }) ○ Anyway, Threads abstraction level is too low Introduction Thread policies
  • 11. Asynchronous Scala: Promising futures ● 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) Futures Overview
  • 12. Asynchronous Scala: Promising futures ● Successfully completion 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(100000)'… } res0: Future[List[Int]] Futures Success on completion
  • 13. Asynchronous Scala: Promising futures ● Failure completion example import scala.concurrent._ import ExecutionContext.Implicits.global val thisWillFail: Future[Int] = Future(2 / 0) res0: Future[Int] Futures Failure on completion
  • 14. Asynchronous Scala: Promising futures ● 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. Futures ExecutionContext
  • 15. Asynchronous Scala: Promising futures ● Expecting results. ○ Blocker way (discouraged but sometimes mandatory). ○ Non-blocker way: using callbacks Futures Expecting results
  • 16. Asynchronous Scala: Promising futures ● 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 Futures Blocking: Await
  • 17. Asynchronous Scala: Promising futures ● 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] Futures Blocking: Await problem
  • 18. Asynchronous Scala: Promising futures ● Non-Blocking: callbacks import scala.concurrent._ import scala.concurrent.duration._ 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 Futures Non-blocking: Callbacks Non-blocking
  • 19. Asynchronous Scala: Promising futures ● Callbacks will be executed asynchronously when future is completed ● Try[T] => U ● Try[T] ~ Either[Throwable,T] ○ Left(throwable) ~ Failure(throwable) ○ Right(t) ~ Success(t) Futures Callbacks
  • 20. Asynchronous Scala: Promising futures ● onComplete f.onComplete( (t: Try[Int]) => println(n) ) //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)) Futures Callbacks
  • 21. Asynchronous Scala: Promising futures ● Composition ○ Future is a monad ■ Type Constructor: T => Future[T] ■ Unit Function: Future.apply ■ Bind Function: flatMap ○ Since Future has map,flatMap,filter methods; it can be composed easily in a for-comprehension Futures Monad behavior
  • 22. Asynchronous Scala: Promising futures Futures Monad behavior
  • 23. Asynchronous Scala: Promising futures ● map def getFirstMillionOfPrimes(): Future[List[Int]] = ??? getFirstMillionOfPrimes().map( (list: List[Int]) => list.head) res0: Future[Int] Futures Monad behavior
  • 24. Asynchronous Scala: Promising futures ● flatMap def getFirstMillionOfPrimes(): Future[List[Int]] = ??? def concatenate(l: List[Int]): Future[String] = ??? getFirstMillionOfPrimes().flatMap((list: List[Int]) => concatenate(list)) res0: Future[String] Futures Monad behavior
  • 25. Asynchronous Scala: Promising futures ● Problem var result: String = “” val f1: Future[Unit] = Future{result += “Hi ”} val f2: Future[Unit] = Future{result += “ everyone”} ● result value? Futures Composition
  • 26. Asynchronous Scala: Promising futures ● for-comprehension is your friend for { primes <- getFirstMillionPrimes() primesString <- concatenate(primes) } yield primes res0: Future[String] Futures Composition Future[List[Int]] Future[String]
  • 27. Asynchronous Scala: Promising futures ● recover val f: Future[Int] = Future{ 1 / 0 }.recover{ case e: ArithmeticException => 0 } Futures Recovering from failure
  • 28. Asynchronous Scala: Promising futures ● recoverWith val f: Future[Int] = Future{ 1 / 0 }.recoverWith{ case e: ArithmeticException => Future(0) } Futures Recovering from failure
  • 29. Asynchronous Scala: Promising futures ● fallbackTo val f1: Future[Int] = Future{ 1 / 0 } val f2: Future[Int] = Future(0) val f = f1 fallbackTo f2 Futures Recovering from failure
  • 31. Asynchronous Scala: Promising futures ● 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) Promises Overview
  • 32. Asynchronous Scala: Promising futures Promises Baggage & claim pattern Menu order Menu Being Cooked Ticket Menu Ready
  • 33. Asynchronous Scala: Promising futures Promises Baggage & claim pattern Promise[T] Begin completion Future[T] p.success or p.failure Try[T]
  • 34. Asynchronous Scala: Promising futures Promises Example val producer = future { val r: T = produceSomething() p success r continueDoingSomethingUnrelated() } val consumer = future { startDoingSomething() f onSuccess { case r: T => handleResult() } } val p = promise[T] val f = p.future
  • 35. Asynchronous Scala: Promising futures ● complete val p: Promise[Int] p.complete(Try(2)) ● completeWith val p: Promise[Int] p.completeWith(Future(2)) Promises Overview
  • 36. Asynchronous Scala: Promising futures Finished... ...for today Futures/Promises Akka actors
  • 37. Still interested? ● Scala school (Twitter) ● Reactive Design Patterns, Roland Kuhn and Jamie Allen ● Scala-lang docs: Futures and promises ● Akka doc - Futures