SlideShare a Scribd company logo
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

More Related Content

What's hot

React Development with the MERN Stack
React Development with the MERN StackReact Development with the MERN Stack
React Development with the MERN Stack
Troy Miles
 
Composable and streamable Play apps
Composable and streamable Play appsComposable and streamable Play apps
Composable and streamable Play apps
Yevgeniy Brikman
 
Play + scala + reactive mongo
Play + scala + reactive mongoPlay + scala + reactive mongo
Play + scala + reactive mongo
Max 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 2015
Manuel 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 remedy
krivachy
 
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
Alex 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 dive
epamspb
 
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
 
Async fun
Async funAsync fun
React Native One Day
React Native One DayReact Native One Day
React Native One Day
Troy Miles
 
Async - react, don't wait - PingConf
Async - react, don't wait - PingConfAsync - react, don't wait - PingConf
Async - react, don't wait - PingConf
Johan 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 apps
Peter Pilgrim
 
Java 8 concurrency abstractions
Java 8 concurrency abstractionsJava 8 concurrency abstractions
Java 8 concurrency abstractions
Nawazish Mohammad Khan
 
Intro to React
Intro to ReactIntro to React
Intro to React
Troy Miles
 
Java Play RESTful ebean
Java Play RESTful ebeanJava Play RESTful ebean
Java Play RESTful ebean
Faren faren
 
React Native Evening
React Native EveningReact Native Evening
React Native Evening
Troy Miles
 
Java Play Restful JPA
Java Play Restful JPAJava Play Restful JPA
Java Play Restful JPA
Faren faren
 
Akka Cluster in Java - JCConf 2015
Akka Cluster in Java - JCConf 2015Akka Cluster in Java - JCConf 2015
Akka Cluster in Java - JCConf 2015
Jiayun 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 JVM
Peter Pilgrim
 

What's hot (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
 

Viewers also liked

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
Stratio
 
Scala @ Real Life Codemotion 2014
Scala @ Real Life Codemotion 2014Scala @ Real Life Codemotion 2014
Scala @ Real Life Codemotion 2014
David Vallejo Navarro
 
Scala@real life
Scala@real lifeScala@real life
Scala@real life
David Vallejo Navarro
 
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
scalerablog
 
Introducción a akka
Introducción a akkaIntroducción a akka
Introducción a akka
David Vallejo Navarro
 
Codemotion 2014 Scala @real life
Codemotion 2014 Scala @real lifeCodemotion 2014 Scala @real life
Codemotion 2014 Scala @real life
Javier Santos Paniego
 
Scala for dummies
Scala for dummiesScala for dummies
Scala for dummies
Javier Santos Paniego
 
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-2014
Stratio
 
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
Stratio
 
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
Stratio
 
Multiplaform Solution for Graph Datasources
Multiplaform Solution for Graph DatasourcesMultiplaform Solution for Graph Datasources
Multiplaform Solution for Graph Datasources
Stratio
 
Lunch&Learn: Combinación de modelos
Lunch&Learn: Combinación de modelosLunch&Learn: Combinación de modelos
Lunch&Learn: Combinación de modelos
Stratio
 
Stratio platform overview v4.1
Stratio platform overview v4.1Stratio platform overview v4.1
Stratio platform overview v4.1
Stratio
 
[Strata] Sparkta
[Strata] Sparkta[Strata] Sparkta
[Strata] Sparkta
Stratio
 
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 Trees
Stratio
 
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
Stratio
 
[Spark meetup] Spark Streaming Overview
[Spark meetup] Spark Streaming Overview[Spark meetup] Spark Streaming Overview
[Spark meetup] Spark Streaming Overview
Stratio
 
Meetup: Spark + Kerberos
Meetup: Spark + KerberosMeetup: Spark + Kerberos
Meetup: Spark + Kerberos
Stratio
 

Viewers also liked (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
 

Similar to 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
 
Coding in Style
Coding in StyleCoding in Style
Coding in Style
scalaconfjp
 
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 Scala
Nehal 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 risks
SeniorDevOnly
 
pure-functional-programming.pdf
pure-functional-programming.pdfpure-functional-programming.pdf
pure-functional-programming.pdf
PuneetChaturvedi23
 
Reactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwiftReactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwift
Florent Pillet
 
Introduction to meta-programming in scala
Introduction to meta-programming in scalaIntroduction to meta-programming in scala
Introduction to meta-programming in scala
Alessandro 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 demo
Muhammad 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
 
JavaScript for real men
JavaScript for real menJavaScript for real men
JavaScript for real men
Ivano Malavolta
 
Scala coated JVM
Scala coated JVMScala coated JVM
Scala coated JVM
Stuart Roebuck
 
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 Scala
Neelkanth 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): Day1
Taisuke Oe
 

Similar to 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
 

More from 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? BDS18
Stratio
 
Kafka and KSQL - Apache Kafka Meetup
Kafka and KSQL - Apache Kafka MeetupKafka and KSQL - Apache Kafka Meetup
Kafka and KSQL - Apache Kafka Meetup
Stratio
 
Wild Data - The Data Science Meetup
Wild Data - The Data Science MeetupWild Data - The Data Science Meetup
Wild Data - The Data Science Meetup
Stratio
 
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
Stratio
 
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.0
Stratio
 
Big Data Security: Facing the challenge
Big Data Security: Facing the challengeBig Data Security: Facing the challenge
Big Data Security: Facing the challenge
Stratio
 
Operationalizing Big Data
Operationalizing Big DataOperationalizing Big Data
Operationalizing Big Data
Stratio
 
Artificial Intelligence on Data Centric Platform
Artificial Intelligence on Data Centric PlatformArtificial Intelligence on Data Centric Platform
Artificial Intelligence on Data Centric Platform
Stratio
 
Introduction to Artificial Neural Networks
Introduction to Artificial Neural NetworksIntroduction to Artificial Neural Networks
Introduction to Artificial Neural Networks
Stratio
 
“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 Cassandra
Stratio
 
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
Stratio
 
Spark Summit - Stratio Streaming
Spark Summit - Stratio Streaming Spark Summit - Stratio Streaming
Spark Summit - Stratio Streaming
Stratio
 

More from 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
 

Recently uploaded

Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
Aftab Hussain
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
Introduction to Pygame (Lecture 7 Python Game Development)
Introduction to Pygame (Lecture 7 Python Game Development)Introduction to Pygame (Lecture 7 Python Game Development)
Introduction to Pygame (Lecture 7 Python Game Development)
abdulrafaychaudhry
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Neo4j
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
Google
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
NYGGS Automation Suite
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
rickgrimesss22
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Crescat
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
Google
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
Łukasz Chruściel
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
Philip Schwarz
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
Neo4j
 

Recently uploaded (20)

Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
Introduction to Pygame (Lecture 7 Python Game Development)
Introduction to Pygame (Lecture 7 Python Game Development)Introduction to Pygame (Lecture 7 Python Game Development)
Introduction to Pygame (Lecture 7 Python Game Development)
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
 

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